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?
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:
Note that you can also receive a variable number of arguments as a real array, instead of using the
argumentsobject.For example:
In the days of ES3/ES5, to correctly pass the arguments to another function, you needed to use
apply:The
applymethod takes two parameters, the first is thethisObj, the value of it will be used as thethisvalue inside the invoked function, if you usenullorundefined, thethisvalue inside the function will refer to the global object, in non-strict mode, otherwise isundefined.The second argument that
applyexpects is an array-like object that contains the argument values to be applied to the function.Check the above example here.