问题描述
我将 myObj
复制到 tempMyObj
var tempMyObj = myObj;
tempMyObj.entity
。我根据一些条件修改 tempMyObj.entity
。问题是如果我修改 tempMyObj.entity
myObj.entity
也得到修改。
tempMyObj.entity
is an array of objects. I am modifying tempMyObj.entity
based on some conditions. The problem is if I modify tempMyObj.entity
the myObj.entity
is also getting modified.
for (j = 0; j < myObj.length; j++) {
if (myObj[j].type == "TableShape") {
var dupEntites = new Array();
for (i = 0; i < myObj[j].entities.length; i++) {
if (chk.value != myObj[j].entities[i].id) {
var obj = {};
obj.text = myObj[j].entities[i].text;
obj.id = myObj[j].entities[i].id;
dupEntites.push(obj);
}
else {
if (chk.checked)
{
var obj = {};
obj.text = myObj[j].entities[i].text;
obj.id = myObj[j].entities[i].id;
dupEntites.push(obj);
}
}
}
tempMyObj[j].entities = dupEntites;
}
}
推荐答案
很清楚,你对语句 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
您需要创建副本,如果您需要修改一个副本其他。
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
var tempMyObj = jQuery.extend(true, {}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
以下是创建对象副本的几种方法:
由于你已经在使用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对象的副本会导致原始对象更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!