2015-12-22 31 views
0

我有一個主陣列作爲如何將一個數組的內容複製到另一個數組中。 JavaScript的

arrayVariable = [1,2,3]; 

,我想另一個變量具有與上述相同的內容。如果我這樣做

anotherVariable = arrayVariable; 

它只會引用該數組,而且它們不會相互獨立。 我試過這個解決方案,但它沒有工作。

var anotherVariable = arrayVariable.slice(); 

編輯: 另一個問題, 同時使陣列通過函數,它通過陣列,或者它被引用傳遞?

var array = []; 
someFunction(array); 

function someFunction(array){}; 
+0

.slice()應該工作。你能舉一個例子嗎? –

+0

做了一個函數傳遞數組的引用嗎? 問題已更新。 –

+0

這是一個對象,所以通過引用 – juraj

回答

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

0

你可以嘗試

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

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

希望幫助。

0

您可以使用一個循環做到這一點。

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

    anothervariable[i]=arrayvariable[i]; 
} 
相關問題