简体   繁体   中英

JavaScript array passed as ref but can't assign ref to a new array?

If I pass an array into a function and make changes to the array within the function, the array that exists outside the function reflects those effects. Eg:

var myArr = [1, 2, 3];
function popAll(arr) {
    while(arr.length) {
        arr.pop();
    }
}
popAll(myArr);
console.log(myArr.length); // prints "0"

However, if I try to reassign the array reference to point to another array in the function, it does not stick:

var myArr = [1, 2, 3];
function reassign(arr) {
    while(arr.length) {
        arr.pop();
    }
    var newArr = [1,2,3,4,5];
    arr = newArr;
}
reassign(myArr);
console.log(myArr.length); // still prints "0"!!

What am I missing? I want reassign(...) to assign the reference to the new array.

Edit:

I do not want to return the new array. I want to reassign the incoming reference. Also, I want to learn why JS has this behavior that appears to be inconsistent (or I don't know enough about to understand how it is consistent).

All function calls in JavaScript are pass-by-value.

This may seem counter-intuitive, but it makes more sense if you consider that the arr parameter is itself a reference, so it's a reference, passed by value. Assigning newArr to arr will not modify the old reference, it will simply change what arr references within the scope of the function.

As Zeb Rawnsley pointed out in comments , you must return the new reference from the function and assign the outer variable to the return value:

 var myArr = [1, 2, 3]; function reassign(arr) { while(arr.length) { arr.pop(); } var newArr = [1,2,3,4,5]; return newArr; } myArr = reassign(myArr); console.log(myArr.length); 

Just pointing out that you don't need to pass in the old reference or empty it, it will automatically be garbage-collected once there are zero references left to the memory that myArr initially allocated:

 var myArr = [1, 2, 3]; function reassign() { return [1,2,3,4,5]; } myArr = reassign(); console.log(myArr.length); 

You can't assign the value of an array to another array, but you can add the elements from one array to another.

This should do the trick for you:

var myArr = [1, 2, 3];
function reassign(arr) {
    while(arr.length) {
        arr.pop();
    }
    var newArr = [1,2,3,4,5];
    for(var num in newArr){
        arr.push(num);
    }
}
reassign(myArr);
console.log(myArr.length); //prints 5

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