Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If arrays are passed by reference, how can the following work?

var myarray = []
var array1 = [1,2,3]
myarray.push(array1)
array1 =[2,3,4]
myarray.push(array1)
console.log(myarray)

I get

[ [ 1, 2, 3 ], [ 2, 3, 4 ] ].

Shouldn't it be

[ [ 2, 3, 4 ], [ 2, 3, 4 ] ]

if I am passing by reference?

Thank you

edit: I am guessing it is because = [2,3,4] creates a new object and assigns array1 to refer to it rather than vice versa

like image 825
FranktheTank Avatar asked Dec 12 '25 01:12

FranktheTank


2 Answers

You're not modifying the variable (array), you're reassigning a new value.

var myarray = [];
var array1 = [1, 2, 3];
myarray.push(array1);
array1.push(2, 3, 4); // Modifying the array in memory.
//myarray.push(array1);
console.log(myarray);
like image 109
Ele Avatar answered Dec 14 '25 13:12

Ele


You need to mutate elements of the array1 to keep the reference. Not re-assign it.

var myArray = []
var array1 = [1,2,3]

myArray.push(array1)
array1.forEach((e, i) => array1[i] = array1[i] + 1)
myArray.push(array1)

console.log(myArray)
like image 43
bird Avatar answered Dec 14 '25 13:12

bird