Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable value changes after pushing in array [duplicate]

So I was testing this little peace of code:

<script>
  var newData = {}, graphs = []
  for(var j=0; j<2; j++){
    newData["name"] = 'value '+ j
    console.log(newData["name"]);
    graphs.push(newData);
    console.log(graphs);
  }
</script>

I've got the following output in the webconsole:

value 0 
Array [ Object ] 
value 1 
Array [ Object, Object ]

All Objects in the Arrays have the exact same Values:

name:"value 1"

I am really struggling with this because I don't change any values and the name is still changed in the same loop.

Thanks for your answers in advance!

like image 757
GuyWithCookies Avatar asked Mar 11 '16 12:03

GuyWithCookies


People also ask

Does array push change the original array?

To avoid this error you need to remember that push changes the array, and returns the new length. If you reassign the variable with the return value from push() you are overwriting the array value.

How do you copy an array without changing the original array?

Approach 1: Using the copy of the array. In this approach, we will create a copy of the original array and then use the splice method to extract the items. To create the copy or clone of the array we can use the spread operator or splice method.

Does array push overwrite?

Push is overwriting previous data in array.

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.


1 Answers

Putting an object into an array in javascript means you're putting a reference to that object in the array rather than the value of that object. In your example, you create a single object, newData and you change the name property on that object in your loop. That means that at the end of the loop you're left with a newData object with {'name': 'value 2'}

When you then take a look at graphs[0], it will tell you that it contains a reference to newData which looks like {'name': 'value 2'}. The same holds for graphs[1]

you can solve this by making a new object each time in your array as such:

graphs = []
for(var j=0; j<2; j++){
  var newData = {}
  newData["name"] = 'value '+ j
  console.log(newData["name"]);
  graphs.push(newData);
  console.log(graphs);
}
like image 103
Matthijs Brouns Avatar answered Sep 28 '22 19:09

Matthijs Brouns