user1371699
user1371699

Reputation: 23

Why does changing an object you've already pushed to an array change the value in the array as well?

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

Answers (2)

Ayush
Ayush

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));
}

Demo

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

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

Related Questions