问题描述
我正在将 objA 复制到 objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
数组也有同样的问题
const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.
推荐答案
很明显,您对语句 var tempMyObj = myObj; 的作用有一些误解.
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does.
在 JavaScript 中,对象是通过引用传递和分配的(更准确地说是引用的值),所以 tempMyObj 和 myObj 都是对同一个对象的引用.
In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.
这是一个简化的插图,可以帮助您直观地了解正在发生的事情
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
正如你在赋值后看到的,两个引用都指向同一个对象.
As you can see after the assignment, both references are pointing to the same object.
如果您需要修改一个而不是另一个,则需要创建一个副本.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
旧答案:
以下是创建对象副本的其他几种方法
Here are a couple of other ways of creating a copy of an object
既然你已经在使用 jQuery:
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
使用原生 JavaScript
With vanilla JavaScript
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var newObject = clone(myObj);
请参阅此处和这里
这篇关于修改 JavaScript 对象的副本会导致原始对象发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)