JavaScript - array passed by reference, but lost upon reassignment

In the next JS-code, why f3(arr2)not change the value of arr2how f2(arr1)to arr1? Is there a way to make it f3work 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]
+4
source share
4 answers

If you want to change the array, you really need to change the array. You cannot just write a link to another array above the variable (since it just discards the local link to this array).

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

quote: "console.log (arr2); // [1, 2, 3, 4], expect [2, 3, 4, 5]"

, , ,

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

[2,3,4,5] - arr f3, arr2. Arr2 , , script.

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

. , .

+2

:

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>');
Hide result
+1

- ( ), javascript , ... , (=)

, , , , . . :

-1

All Articles