简体   繁体   English

通过索引为数组对象设置值设置所有数组项

[英]setting value for array object via index sets all array items

I have a complex javascript object with an array. 我有一个带有数组的复杂javascript对象。 When I try to set the value for one attribute of an index, it's applied to all items of the array. 当我尝试为索引的一个属性设置值时,它将应用于数组的所有项目。

Here is a basic example: 这是一个基本示例:

var obj = new Object();    
obj.arr = [];
obj.arr[0] = {pos:[0,0]};
obj.arr[1] = {pos:[0,0]};

Now if i set a value for an attribute of the object, via a specific index, 现在,如果我通过特定索引为对象的属性设置值,

obj.arr[0].pos = [10,10];
obj.arr[1].pos = [5,5];

Here it seems to be setting the value [5,5] for both items of the array. 在这里,似乎为数组的两个项目都设置了[5,5]值。 The resulting values are: 结果值为:

console.log(obj.arr[0].pos) returns [5,5] and console.log(obj.arr[0].pos)返回[5,5]

console.log(obj.arr[1].pos) also returns [5,5] console.log(obj.arr[1].pos)也返回[5,5]

My actual object is far more complex, but this is the basic idea of what's happening... 我的实际对象要复杂得多,但这是正在发生的事情的基本思想。

Any ideas? 有任何想法吗?

They share the same link, ie several variables/properties of an object are referring to the same value. 它们共享相同的链接,即对象的多个变量/属性引用相同的值。

Exact answer (where's the error) depends on how your object is composed. 确切答案(错误在哪里)取决于对象的构成方式。

var nested = {a:1};
var obj = {arr:[]};
obj.arr[0] = {pos:0, n:nested};
obj.arr[1] = {pos:0, n:nested};

obj.arr[0].pos = 1;
obj.arr[1].pos == 1; // false
obj.arr[0].nested.a = 2;
obj.arr[1].nested.a == 2; // true

Assignment of the same array/object literals is not the same. 相同的数组/对象文字的分配是不同的。

var a = [0];
var b = [0];
b[0] = 1;
a[0] == 1; // false
b = a;
a[0] = 2;
b[0] == 2; // true

a = b = [0];
a[0] = 1;
b[0] == 1; // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM