[英]Array of array of objects reference in Javascript
I have an array as follows 我有一个数组如下
var sample = [{a:1, b: 1, c:1}, {a:1, b: 1, c:1}, {a:1, b: 1, c:1}];
I then run the following code and try groupsOfItems[0].sample[0].a = 10
, groupsOfItems[0].sample[0].a
, groupsOfItems[1].sample[0].a
and groupsOfItems[2].sample[0].a
get changed to 10. 然后我运行以下代码并尝试
groupsOfItems[0].sample[0].a = 10
, groupsOfItems[0].sample[0].a
, groupsOfItems[1].sample[0].a
和groupsOfItems[2].sample[0].a
变为10。
How do I prevent this? 我该如何防止这种情况?
var sample = [{a:1, b: 1, c:1}, {a:1, b: 1, c:1}, {a:1, b: 1, c:1}]; var groupsOfItems = []; for(let i = 0; i < 10; i++) { var item = {}; item.sample = _.clone(sample); groupsOfItems.push(item); } groupsOfItems[0].sample[0].a = 10 console.log(groupsOfItems[0].sample[0].a,groupsOfItems[1].sample[0].a,groupsOfItems[2].sample[0].a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You need to clone the object before assiging its referece to the array's property 在将对象赋予数组的属性之前,您需要克隆该对象
Replace 更换
item.sample = sample;
with 同
item.sample = JSON.parse(JSON.stringify(sample));
Note that this method of cloning will be less efficient when the sample object grows. 请注意,当样本对象增长时,这种克隆方法效率会降低。 Try some other methods shown here .
尝试这里显示的其他一些方法。
as mentioned in this post 如本文所述
for(let i = 0; i < 10; i++) {
var item = {};
item.sample = $.extend(true, [], sample);
groupsOfItems.push(item);
}
I would avoid cloning the object in general. 我会避免一般克隆对象。 Cloning objects only tends to end in pain further down the track.
克隆对象只会在轨道下方的痛苦中结束。 Here's how I have achieved similar in the past without cloning.
以下是我在过去没有克隆的情况下取得的相似之处。
var sample = [{ a: 1, b: 1, c: 1}, { a: 1, b: 1, c: 1}, { a: 1, b: 1, c: 1}];
var groupsOfItems = [];
var Item = function(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
for (let i = 0; i < 10; i++) {
var item = {};
item.sample = _.map(sample, function(item) {
return new Item(item.a, item.b, item.c)
});
groupsOfItems.push(item);
}
groupsOfItems[0].sample[0].a = 10
console.log(groupsOfItems[0].sample[0].a, groupsOfItems[1].sample[0].a, groupsOfItems[2].sample[0].a);
//10 1 1
This way you're assigning them all a container for your modifications and the problem with cloning goes away. 通过这种方式,您可以为它们分配所有容器以进行修改,克隆问题就会消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.