Javascript: Forwarding function calls that take variable number of arguments [duplicate]

折月煮酒 提交于 2020-01-02 01:13:17

问题


I think I need something like ruby's splat * here.

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

I want this to return "123", but instead I get "[object Arguments]". Which makes sense, I suppose. It's passing the object that represents the arguments, but not the arguments individually.

So how do I simply forward any number of arguments to another function that takes any number of arguments?


回答1:


UPDATE: Since ES6, you can use the spread syntax to call a function, applying the elements of an iterable object as argument values of the function call:

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

Note that you can also receive a variable number of arguments as a real array, instead of using the arguments object.

For example:

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

In the days of ES3/ES5, to correctly pass the arguments to another function, you needed to use apply:

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

The apply method takes two parameters, the first is the thisObj, the value of it will be used as the this value inside the invoked function, if you use null or undefined, the this value inside the function will refer to the global object, in non-strict mode, otherwise is undefined.

The second argument that apply expects is an array-like object that contains the argument values to be applied to the function.

Check the above example here.




回答2:


Try this return foo.apply(this,arguments). Also you can just use Array.prototype.slice.apply(arguments).join('') for your foo function.



来源:https://stackoverflow.com/questions/3120017/javascript-forwarding-function-calls-that-take-variable-number-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!