【问题标题】:Javascript: Forwarding function calls that take variable number of arguments [duplicate]Javascript:转发接受可变数量参数的函数调用[重复]
【发布时间】:2011-03-08 09:28:15
【问题描述】:

我想我需要像 ruby​​'s splat * 这里的东西。

function foo() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

function bar() {
  return foo(arguments) // this line doesn't work as I expect
}

bar(1, 2, 3);

我希望它返回 "123",但我得到的是 "[object Arguments]"。我想这是有道理的。它传递表示参数的对象,而不是单独的参数。

那么我如何简单地将任意数量的参数转发给另一个接受任意数量参数的函数?

【问题讨论】:

    标签: javascript arguments


    【解决方案1】:

    更新:从 ES6 开始,您可以使用 spread syntax 调用函数,将可迭代对象的元素应用为函数调用的参数值:

    function bar() {
      return foo(...arguments);
    }
    

    请注意,您还可以接收可变数量的参数作为实数数组,而不是使用arguments 对象。

    例如:

    function sum(...args) { //  args is an array
      return args.reduce((total, num) => total + num)
    }
    
    function bar(...args) {
      return sum(...args) // this just forwards the call spreading the argument values
    }
    
    console.log(bar(1, 2, 3)); // 6

    在 ES3/ES5 时代,要正确地将参数传递给另一个函数,您需要使用apply

    function bar() {
      return foo.apply(null, arguments);
    }
    

    apply方法有两个参数,第一个是thisObj,它的值将作为被调用函数内部的this值,如果使用nullundefined,则函数内部的this值将引用全局对象,在非严格模式下,否则为undefined

    apply 期望的第二个参数是一个类似数组的对象,其中包含要应用于函数的参数值。

    查看上面的例子here

    【讨论】:

      【解决方案2】:

      试试这个return foo.apply(this,arguments)。您也可以将Array.prototype.slice.apply(arguments).join('') 用于您的 foo 函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-07
        • 2011-12-24
        • 2010-12-09
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2017-02-24
        • 1970-01-01
        相关资源
        最近更新 更多