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
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With