更改和分配没有副作用的对象 [英] Alter and Assign Object Without Side Effects
本文介绍了更改和分配没有副作用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有以下代码:
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;
问题是当我更改 id $ c的值时对于我的第二个元素,$ c>和
value
,值也会在第一个元素中更改。有没有一种方法可以继续添加新元素而不更改数组中先前插入的值的值?
The problem is that when I change the value of id
and value
for my second element, the values also change in the first element. Is there a way that I can keep adding new elements without it changing the value of the previously inserted values in the array?
推荐答案
请改为尝试:
var myArray = [];
myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });
或这不适用于您的情况?
or will this not work for your situation?
这篇关于更改和分配没有副作用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文