I have a complex javascript object with an array. 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. The resulting values are:
console.log(obj.arr[0].pos) returns [5,5]
and
console.log(obj.arr[1].pos) also returns [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, i.e. 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.
Assignment of the same array/object literals is not the same.