代码之家  ›  专栏  ›  技术社区  ›  Alex Wayne

Javascript:转发采用可变参数数的函数调用[duplicate]

  •  10
  • Alex Wayne  · 技术社区  · 14 年前

    我想我需要像鲁比那样的东西 * 在这里。

    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]" . 我想这是有道理的。它传递的是表示参数的对象,而不是单独的参数。

    那么,如何将任意数量的参数转发给另一个接受任意数量参数的函数呢?

    2 回复  |  直到 14 年前
        1
  •  22
  •   Christian C. Salvadó    5 年前

    更新: 从ES6开始,您可以使用 spread syntax 要调用函数,请将iterable对象的元素用作函数调用的参数值:

    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);
    }
    

    应用 thisObj ,它的值将用作 this 如果使用 null undefined ,的 在非严格模式下,函数中的值将引用全局对象,否则为 .

    第二个论点是 应用

    检查上面的例子 here .

        2
  •  3
  •   Teja Kantamneni    14 年前

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