Reputation: 23
check this code:
var bbb = [];
var aaa = {};
aaa.test = "1";
bbb.push(aaa);
console.log(bbb[0].test);
aaa.test = "2";
bbb.push(aaa);
console.log(bbb[0].test);
Why the console ouput is "1,2"? I think it should be "1,1".
Upvotes: 2
Views: 75
Reputation: 42440
Objects are added to the array by reference. So, when you do bbb[0]
, it is referring to the instance of aaa
that you created previously and then modified.
If you don't want this behavior, you need to clone the object before adding it.
bbb.push(clone(aaa))
As for the implementation of clone()
, if you have jQuery :
function clone(obj) {
return jQuery.extend({}, obj);
}
And without jQuery:
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
Upvotes: 2
Reputation: 94429
Your passing a reference of aaa
to the array. So when you make a change to aaa
it is reflected in the first element of the array.
Upvotes: 0