Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: push array into array vs. push values into array?

I'm new to javascript and don't quite understand how the push() method works.

I've got two empty arrays, row and newData. And two pieces of codes with very different outputs:

for (i = 1; i <= 10 ; i++) {
    row[0] = i;
    newData.push(row);
}

results in newData == [10,10,10,...,10], which I find very surprising, and

for (i = 1; i <= 10 ; i++) {
    newData.push(i);
}

results in newData == [1,2,3,...,8,9,10] which is the intended outcome.

But I do not understand why every iteration of the first loop seems to replace every element of newData with the last element, when the second loop works just as intended?

Thanks!

like image 517
Alexandre d'Entraigues Avatar asked Sep 27 '26 17:09

Alexandre d'Entraigues


1 Answers

Your first snippet:

var row = new Array();
var newData = new Array();

for (i = 1; i <= 10 ; i++) {
    row[0] = i;
    newData.push(row);
}

pushes 10 times the reference to the array row, and at the same time changes the value contained in the position 0 of that array in turn to the values 1, 2, 3 .. 10, with the net result of setting the final contents of the row array to: [10].

The actual final value of newData is more correctly shown as:

[[10],[10],[10],[10],[10],[10],[10],[10],[10],[10]]

and not as:

 [10,10,10,...,10]

In JavaScript, pushing an object into an array, (as in this case an instance of the Array class), actually pushes into the array a reference to the object. Pushing the same variable row doesn't create multiple instances of it.

This behavior is explained in detail here: Is JavaScript a pass-by-reference or pass-by-value language?.

like image 115
Luigi Sgro Avatar answered Sep 30 '26 06:09

Luigi Sgro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!