I have the following code (which works correctly):
var arr = [];
for(var i = 0; i < 2; i++) {
var obj = { a: 'A'};
obj.c = 'C' + i;
arr.push(obj);
}
// now arr is:
// [ {a: 'A', 'c': 'C0'}, {a: 'A', 'c': 'C1'} ]
To improve the performance of my code, I placed the obj
outside the loop, then adding/modifying the new property only, like this:
var arr = [];
var obj = { a: 'A'};
for(var i = 0; i < 2; i++) {
obj.c = 'C' + i;
arr.push(obj);
}
// now arr is:
// [ {a: 'A', 'c': 'C1'}, {a: 'A', 'c': 'C1'} ]
Why both objects got C1 ? Please explain what I'm doing wrong, and how to place the object out of the loop and get correct results?
Note: I know this is a simple problem where performance is not an issue, but I'm actually dealing with big number of objects in reality where performance matters.