【问题标题】:Using the arguments object in functions在函数中使用 arguments 对象
【发布时间】:2015-02-26 02:56:23
【问题描述】:

为什么 foo 函数可以正常工作。

function foo (a,b) {
  return arguments.length;
}

但是,boo 函数返回 undefined 不是一个函数,即使我在函数中传递了参数。

function boo (a,b) {
  return arguments.slice(0);
}

【问题讨论】:

    标签: javascript object arguments


    【解决方案1】:

    arguments 是一个对象,不是array。如果你打印出来看看,你可以看到一个对象:

    function foo (a,b) {
        console.log(arguments);
    }
    
    foo(10,20);
    
    o/p: { '0': 10, '1': 20 }
    

    来自docs

    此对象包含传递给每个参数的条目 函数,第一个条目的索引从 0 开始。例如,如果 函数传递了三个参数,您可以将参数称为 如下:

     arguments[0] arguments[1] arguments[2]
    

    它确实没有除了length 之外的任何数组属性。

    所以,return arguments.slice(0); 会失败,因为 slice 属于 arrayprototype

    【讨论】:

      【解决方案2】:

      arguments 不是数组,而是类数组对象。许多数组方法适用于类似数组的对象,因为它们需要具有数字属性和length 属性的对象,例如arguments。您可以通过使用call 并将对象作为this 值传递来使用内置函数:

      var args = Array.prototype.slice.call(arguments);
      //^ args is a real array now
      

      这也适用于其他方法,例如 reduce:

      function sum(/*...args*/) {
        return [].reduce.call(arguments, function(x, y){return x + y})
      }
      

      【讨论】:

      • 在切片函数上使用call方法如何将arguments对象变成数组?
      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2017-11-12
      • 2012-11-11
      • 2019-02-10
      • 2016-01-27
      相关资源
      最近更新 更多