如何将一个数组的内容复制到另一个数组中。 Javascript

how to copy contents of one array into another. Javascript

我有一个主数组

  arrayVariable = [1,2,3];

并且我希望另一个变量具有与上面相同的内容。如果我这样做

anotherVariable = arrayVariable;

它只会引用那个数组,它们不会相互独立。 我试过这个解决方案,但没有用。

 var anotherVariable = arrayVariable.slice();

编辑: 另一个问题, 通过函数传递数组时,它传递数组还是通过引用传递?

喜欢

 var array = [];
 someFunction(array);

 function someFunction(array){};

你可以试试

var aa = [1,2,3,4,5,6];

var bb = [].concat(aa);//copy aa array to bb, they are now independent of each other.

希望有所帮助。

检查下面的代码,看它们是独立的。

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

你可以使用循环来完成。

arrayvariable=[1,2,3];
for (var i=0;i<arrayvariable l.length;i++)
//while could also be used.
{ 

    anothervariable[i]=arrayvariable[i];
}