I am trying to populate an array with a list of objects.
var testarray=[];
var temp={};
temp.data = 10;
temp.data2= 11;
testarray.push(temp);
console.log("After first push:");
console.log(testarray[0].data);
console.log(testarray[0].data2);
temp.data = 20;
temp.data2 = 21;
testarray.push(temp);
console.log("After second push:");
console.log(testarray[0].data);
console.log(testarray[0].data2);
console.log(testarray[1].data);
console.log(testarray[1].data2);
I would expect that after the second click, testarray would contain the values 10 and 11 for the first element of the array and 20 and 21 for the second.
In reality, the first element of the array contains 20 and 21. Thus, the second push overwrites the first element of the array. What's wrong?
source
share