数组作为参数传递但在函数内重新分配失败?

时间:2014-07-01 06:02:14

标签: javascript arrays function variable-assignment

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

那为什么foo不起作用?

A被传递到foo的参数a,所以foo的代码应该runA = A.map(whatever),就像在bar?中一样,我有一些模糊的猜测它是如何{ {1}}处理javascript中的array pointers或其他内容。

3 个答案:

答案 0 :(得分:0)

范围' a'是函数的本地。你应该回来' a'并将其分配给' A',类似

A = foo(A);

答案 1 :(得分:0)

变量通过引用传递,因此赋值不会更改函数的外部。第二个功能"作弊"一点点因为您将a声明为函数参数,但在函数内直接引用A

也就是说,使用可以修改数组本身的功能:

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

或者,从函数中返回新数组:

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

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

答案 2 :(得分:0)

就像@Jayachandran所说的那样,' a'是 foo 函数的本地。您还需要从 a.map()返回结果,以便可以将其分配给函数外部的另一个变量(在本例中为 A )。 / p>

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.