Javascript, when pushing outside-defined object into array in a for loop, the last one is repeatedly pushed.
I read many Q/A (see below links) and know the solution, but did not find explanation for the follwing 2 points:
before and after the push, console.log the obj, it shows properly all objects (not repeating the last one), but push works only the last one;
If object defined outside is "always the same object", why not repeat the first one, but repeat the last one?
Related Q/A:
How to push object to array from for loop properly in JavaScript?
React push object into array, always pushed last array
After pushing objects into array, every object in the array has the same value
let arr = [];
let obj = {};
for(let i=0; i<5; i++) {
obj["single"] = i;
obj["double"] = i*2;
console.log(obj);
arr.push(obj);
}
console.log(arr);
result:
{ single: 0, double: 0 }
{ single: 1, double: 2 }
{ single: 2, double: 4 }
{ single: 3, double: 6 }
{ single: 4, double: 8 }
[
{ single: 4, double: 8 },
{ single: 4, double: 8 },
{ single: 4, double: 8 },
{ single: 4, double: 8 },
{ single: 4, double: 8 }
]