简体   繁体   中英

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 ? Is there any way to make f3 work as expected (if possible, without returning the modified array)?

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]"

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. Arr2 remains of course untouched and in its original state throughout your script.

function f3(*arr*) { *arr2* = f1(); } function f3(*arr*) { *arr2* = f1(); } will do it.

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 (=)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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