javascriptfor-loop

object modified in for loop has same value when assigned to array


When I run this code, all objects in the array are the same.

var obj = {
  a: { b: 0 }
}

var arr = [];

for(i = 0; i < 10; i++) {
  arr.push(obj);
  obj.a.b += 5;
}

for(i = 0; i < arr.length; i++) {
  document.writeln(arr[i].a.b);
}

How can I set the values of the object in the array to the increments? Like:

[
  { a: { b: 5 }},
  { a: { b: 10 }},
  { a: { b: 15 }},
  // ...
]

jsfiddle

screenshot of array in console


After Answered

I created a benchmark test for Object.assign vs JSON.stringify for the deep clone.

http://jsben.ch/64Cxe


Solution

  • obj is a reference to an object, so what you are really doing is pushing the same reference to an object over and over again.

    You end up with an array of the same reference to an object. if you want an array of different objects, you need to make a copy of the object before pushing it, you can accomplish it by

    arr.push({...obj})

    or

    arr.push(Object.assign({},obj})