简体   繁体   English

JavaScript - 通过引用传递但在重新分配时丢失的数组

[英]JavaScript - Array passed by reference but lost when reassigned

In the following JS code, why doesn't f3(arr2) change the value of arr2 like f2(arr1) did to arr1 ? 在下面的JS代码,为什么不f3(arr2)改变的值arr2f2(arr1)没有到arr1 Is there any way to make f3 work as expected (if possible, without returning the modified array)? 有没有办法使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]

If you want to modify the array, then you actually have to modify the array. 如果要修改数组,则实际上必须修改数组。 You can't just write a reference to a different array over the variable (as that just throws away the local reference to that array). 你不能只是在变量上写一个不同数组的引用(因为它只是抛弃了对该数组的本地引用)。

function f3(arr) {
    arr.length = 0; // Empty the array
    f1().forEach(function (currentValue) { arr.push(currentValue); });
}

quote: "console.log(arr2); // [ 1, 2, 3, 4 ], expect [2, 3, 4, 5]" 引用:“console.log(arr2); // [1,2,3,4], 期待 [2,3,4,5]”

The reason that you are not getting what you are expecting is this part here 你没有得到你期望的原因是这一部分

function f3(*arr*) { *arr* = f1(); }

You are assigning the array [2,3,4,5] to the argument-name arr of the function f3 , not to the arr2. 您将数组[2,3,4,5]分配给函数f3的参数名称arr ,而不是arr2。 Arr2 remains of course untouched and in its original state throughout your script. 在整个剧本中,Arr2当然仍未被触及并处于原始状态。

function f3(*arr*) { *arr2* = f1(); } function f3(*arr*) { *arr2* = f1(); } will do it. function f3(*arr*) { *arr2* = f1(); }将做到这一点。

But this answer is not my final. 但这个答案不是我的决定。 This is only how it appears. 这只是它的出现方式。

You could do it in a single step: 你可以一步完成:

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>'); 

When you pass anything (Whether that be an object or a primitive), all javascript does is assign a new variable while inside the function... just like using the equal sign (=) 当你传递任何东西时(无论是对象还是原始),所有javascript都会在函数内部分配一个新变量...就像使用等号(=)一样

How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign.. Take these simple examples. 该函数在函数内的行为方式与您使用等号分配新变量时的行为完全相同。请参考这些简单示例。 You can ref: Link 你可以参考: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM