Here is the code i have:
let testp = {
value: ''
}
let data = [];
for (let i = 0; i < 5; i++) {
testp.value = i;
data.push(testp);
}
console.log(data)
The data return is:
[ { value: 4 },
{ value: 4 },
{ value: 4 },
{ value: 4 },
{ value: 4 } ]
why? I think the result is like this:
[ { value: 0 },
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 } ]
testpis a reference to the javascript object; when you calldata.push(testp), you're merely adding to the array another reference to that same object. not a copy of the current state of the object4for every value, because JavaScript passes objects by reference, not by value. Thus you're modifying the same object on every iteration of the loop, not a different object.