0

let's say I have two javascript arrays, like this:

arrA = [1,2,3]
arrB = [4,5,6]

Is there a way I can reference them with different variable names down then road? If I do this:

arrC = arrA
arrD = arrB

it makes copies of the initial arrays, instead of making a pointer/reference to them. So, if I mess with the value of arrC, arrA isn't updated. Is there a way to get around this?

Thanks.

4

2 回答 2

5

不,它不会复制。如果你改变arrC,它也会改变arrA

尝试这个 :

var arrA = [1,2,3];
var arrC = arrA;
arrC.push(26);
console.log(arrA);

您将[1, 2, 3, 26]在控制台中看到。

恰恰相反:如果你复制,你必须明确地做,例如

var arrC = arrA.slice();
于 2013-04-17T13:31:22.657 回答
0

按照这篇文章并在对象中创建一个数组,这是一种简单的方法。

javascript变量引用/别名

于 2013-04-17T13:35:26.510 回答