3
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

4

3 回答 3

6

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);

于 2019-03-28T02:42:19.583 回答
2

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)

于 2019-03-28T02:57:13.827 回答
1

Reference means if two variable are referencing same object/array then modifying(changing property/deleting property) of one will change the other variable too.

let array1 = [1,2,3];
let array2 = array1;     //creating a reference
array1[0] = "something"; //modifying
console.log(array1)
console.log(array2)

Reference doesnot mean that if you two variables are referencing same object/array then assigning a new value to one of them to change the other.

let array1 = [1,2,3];
let array2 = array1;        //creating a reference
array1 = ["something",2,3]; //Assigning a new value
console.log(array1)
console.log(array2)

If you want to change create a reference than change the first element of myarray and push that into the myarray

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

console.log(myarray[0]) //[2,3,4]
console.log(myarray[1]) //[2,3,4]

myarray[0][1] = "something else" //change both elements

console.log(myarray[0]) //[2,"something else",4]
console.log(myarray[1]) //[2,"something else",4]

于 2019-03-28T03:18:33.663 回答