更改和分配没有副作用的对象

时间:2012-03-03 05:38:20

标签: javascript

我目前有以下代码:

var myArray = [];
var myElement = {
  id: 0,
  value: 0
}

myElement.id = 0;
myElement.value = 1;
myArray[0] = myElement;

myElement.id = 2;
myElement.value = 3;
myArray[1] = myElement;

问题在于,当我为第二个元素更改idvalue的值时,值也会在第一个元素中更改。有没有一种方法可以继续添加新元素而不更改数组中先前插入的值的值?

7 个答案:

答案 0 :(得分:75)

请改为尝试:

var myArray = [];

myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });

或者这对你的情况不起作用?

答案 1 :(得分:16)

这是constructor function

的教科书案例
var myArray = [];

function myElement(id, value){
    this.id = id
    this.value = value
}

myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))

答案 2 :(得分:2)

您需要继续创建新对象,或克隆现有对象。有关如何克隆的信息,请参阅What is the most efficient way to deep clone an object in JavaScript?

答案 3 :(得分:1)

那是因为对象值是通过引用传递的。您可以像这样克隆对象:

var myArray = [];
var myElement = {
  id: 0,
  value: 0
}

myElement.id =0;
myElement.value=1;
myArray[0] = myElement;

var obj = {};
obj = clone(myElement);
obj.id = 2;
obj.value = 3; 

myArray[1] = obj;

function clone(obj){
  if(obj == null || typeof(obj) != 'object')
    return obj;

  var temp = new obj.constructor(); 
  for(var key in obj)
    temp[key] = clone(obj[key]);

  return temp;
}    

console.log(myArray[0]);
console.log(myArray[1]);

<强>结果:

 - id: 0
 - value: 1
 - id: 2
 - value: 3

答案 4 :(得分:0)

如果您使用的是jQuery,则可以使用extend

myElement.id =0;
myElement.value=1;
myArray[0] = $.extend({}, myElement);

myElement.id = 2;
myElement.value = 3;
myArray[1] = $.extend({}, myElement);

答案 5 :(得分:0)

通过引用传递对象。要创建 new 对象,我遵循这种方法..

//Template code for object creation.
function myElement(id, value) {
    this.id = id;
    this.value = value;
}
var myArray = [];

//instantiate myEle
var myEle = new myElement(0, 0);
//store myEle
myArray[0] = myEle;

//Now create a new object & store it
myEle = new myElement(0, 1);
myArray[1] = myEle;

答案 6 :(得分:0)

在数组中将有两次相同的对象,因为对象值是通过引用传递的。你必须创建一个像这样的新对象

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

myArray.push({id:24,value:246});