[英]Array reference passed to a function is lost when array.filter is applied
[英]JavaScript - Array passed by reference but lost when reassigned
在下面的JS代碼,為什么不f3(arr2)
改變的值arr2
像f2(arr1)
沒有到arr1
? 有沒有辦法使f3
按預期工作(如果可能,不返回修改后的數組)?
var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 3, 4];
function f1() {
return [2, 3, 4, 5];
}
function f2(arr) {
arr.push(5);
}
function f3(arr) {
arr = f1();
}
f2(arr1);
console.log(arr1); // [ 1, 2, 3, 4, 5 ]
f3(arr2);
console.log(arr2); // [ 1, 2, 3, 4 ], expect [2, 3, 4, 5]
如果要修改數組,則實際上必須修改數組。 你不能只是在變量上寫一個不同數組的引用(因為它只是拋棄了對該數組的本地引用)。
function f3(arr) {
arr.length = 0; // Empty the array
f1().forEach(function (currentValue) { arr.push(currentValue); });
}
引用:“console.log(arr2); // [1,2,3,4], 期待 [2,3,4,5]”
你沒有得到你期望的原因是這一部分
function f3(*arr*) { *arr* = f1(); }
您將數組[2,3,4,5]分配給函數f3的參數名稱arr ,而不是arr2。 在整個劇本中,Arr2當然仍未被觸及並處於原始狀態。
function f3(*arr*) { *arr2* = f1(); }
function f3(*arr*) { *arr2* = f1(); }
將做到這一點。
但這個答案不是我的決定。 這只是它的出現方式。
你可以一步完成:
Array.prototype.splice.apply(arr, [0, arr.length].concat(f1()));
var arr1 = [1, 2, 3, 4]; var arr2 = [1, 2, 3, 4]; function f1() { return [2, 3, 4, 5]; } function f2(arr) { arr.push(5); } function f3(arr) { Array.prototype.splice.apply(arr, [0, arr.length].concat(f1())); } f2(arr1); document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>'); f3(arr2); document.write('<pre>' + JSON.stringify(arr2, 0, 4) + '</pre>');
當你傳遞任何東西時(無論是對象還是原始),所有javascript都會在函數內部分配一個新變量...就像使用等號(=)一樣
該函數在函數內的行為方式與您使用等號分配新變量時的行為完全相同。請參考這些簡單示例。 你可以參考: 鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.