简体   繁体   中英

Array passed as parameter but reassignment within function fails?

function foo(a) {
  a = a.map(function(x) {return 0;});
}

var A = [1,1,1];
foo(A);         //seems like A should now be [0,0,0]
console.log(A); //nope its [still 1,1,1]. debugging shows that the parameter a in foo changes properly to [0,0,0] but does not transfer to A
A = [0,0,0];    //force A to [0,0,0] now
console.log(A);
function bar(a) {
  A = A.map(function(x) {return 1;}); //checking if i can force it back to [1,1,1] using this slight change
}
bar(A);
console.log(A); //this works

So why does foo not work?

A is passed into parameter a for foo , so foo's code should run as A = A.map(whatever) , just like in bar? I have some vague guess about it being how javascript handles array pointers in assignment or something.

Scope of 'a' is local to the function. You should be returning 'a' and assign it to 'A', something like

A = foo(A);

Variables are passed by reference, so the assignment will not change anything outside of the function. The second function "cheats" a little because you declare a as the function argument but inside the function you reference A directly.

That said, from with the function you can modify the array itself:

function foo(a) 
{
    a.forEach(function(value, index) {
        a[index] = 0;
    });
}

Alternatively, return the new array from the function:

function foo(a)
{
    return a.map(function() { return 0; });
}

A = foo(A); // A is now modified

Like @Jayachandran said, that 'a' is local to the foo function. You also need to return the result from the a.map() so that it can be assigned to another variable outside of the function (in this case, A ).

function foo(a) {
    return a.map(function(x) {return 0;});
}

function bar(a) {
    return A.map(function(x) {return 1;});
}

var A = [1,1,1];

A = foo(A);     // Foo returns [0,0,0] as the result, but now we need to save it to A to replace [1,1,1].
console.log(A); // Hurray it's [0,0,0].

A = bar(A);
console.log(A); // Hurray it's [1,1,1] now.

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