[英]how to copy contents of one array into another. Javascript
我有一個主要陣列
arrayVariable = [1,2,3];
我希望另一個to變量具有與上述相同的內容。 如果我做
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
你可以試試
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];
for (var i=0;i<arrayvariable l.length;i++)
//while could also be used.
{
anothervariable[i]=arrayvariable[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.