Why does pushing an object into an array modify unwanted parts of array?

Viewed 91

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 push, testarray would contain values 10 and 11 for first array element, and 20 and 21 for the second one.

In reality though, also the first array element contains 20 and 21. So the second push overwrites the first array element. What is wrong?

4 Answers
Related