【问题标题】:Array passed as parameter but reassignment within function fails?数组作为参数传递但函数内的重新分配失败?
【发布时间】:2014-07-01 06:02:14
【问题描述】:
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? 中一样@ in assignment 什么的。

【问题讨论】:

  • 变量在 JavaScript 中按值传递。它也区分大小写,所以 A !== a.

标签: javascript arrays function variable-assignment


【解决方案1】:

'a' 的范围是函数的本地范围。您应该返回“a”并将其分配给“A”,类似于

A = foo(A);

【讨论】:

    【解决方案2】:

    变量通过引用传递,因此赋值不会改变函数外部的任何内容。第二个函数有点“作弊”,因为您将 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
    

    【讨论】:

      【解决方案3】:

      就像@Jayachandran 所说,'a' 是 foo 函数的局部变量。您还需要从 a.map() 返回结果,以便将其分配给函数外部的另一个变量(在本例中为 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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-09
        • 2017-04-26
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-12
        相关资源
        最近更新 更多