how to copy contents of one array into another. Javascript

时间:2015-12-22 10:21:55

标签: javascript arrays copy

i have a main array as

  arrayVariable = [1,2,3];

and i want another to variables to have the same content as above. If i do

anotherVariable = arrayVariable;

It will just reference that array and they wont be independent of each other. I tried this solution, but it didnt work.

 var anotherVariable = arrayVariable.slice();

Edit: Another question, while passing array through a function, does it pass the array or is it passed by reference?

like

 var array = [];
 someFunction(array);

 function someFunction(array){};

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

你可以尝试

col1  col2  col3  col4  col5
----------------------------    
1      a      b     d    c
1      a      b     c    d
2      p      q     r    s
2      p      q     s    r
2      p      q     t    u    
2      p      q     u    t

希望有所帮助。

答案 2 :(得分:0)

你可以使用循环来完成。

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

    anothervariable[i]=arrayvariable[i];
}