我有一个主数组
arrayVariable = [1,2,3];
我想要另一个变量具有与上面相同的内容。如果我这样做
anotherVariable = arrayVariable;
它只会引用该数组,并且它们不会彼此独立。 我尝试了这个解决方案,但没有成功。
var anotherVariable = arrayVariable.slice();
编辑: 另一个问题, 通过函数传递数组时,它是传递数组还是通过引用传递?
喜欢
var array = [];
someFunction(array);
function someFunction(array){};
最佳答案
检查下面的代码,看看它们是独立的。
arrayVariable = [1,2,3];
var anotherVariable = arrayVariable.slice(); // or .concat()
arrayVariable[0] = 50; // Hopefully it should not change the value of anotherVariable
alert(anotherVariable); // Look value of anotherVariable is not changed
关于javascript - 如何将一个数组的内容复制到另一个数组中。 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413497/