Here is what I would like to do. I have two methods, the first of which can accept any number of arguments. This method is an intermediary, it does not know how many arguments it is going to receive, but it needs to pass all its arguments along to another method. Obviously there is more code, but I have stripped this down to the bare minimum.
function acceptArguments(args) {
secondFunction(arguments);
}
Normally, using this approach the second method accepts the arguments as an array
function secondFunction(param) {
console.log(param);
}
Running this I would expect to see the following:
acceptArguments(1, 2, 3, 4) => and the output would be [1,2,3,4]
However what I would like to able to do is have the secondFunction method accept the parameters individually and not as an array, so it would look something like this:
function secondFunction(v1, v2, v3, v4) {
console.log(v1, v2, v3, v4);
}
Running this I would expect to see the following, if I were to pass 1, 2, 3, 4 ad separate parameters to the method:
acceptArguments(args) => and the output would be 1, 2, 3, 4
My situation is that the secondFunction method is aware of how many arguments it will be receiving, but the acceptArguments method (which is an intermediary does not know or care how many arguments it is passing along.
I have tried, the following without result:
function acceptArguments() {
secondFunction(...arguments);
}
function acceptArguments() {
secondFunction(...Object.keys(arguments));
}
function acceptArguments() {
secondFunction.apply(Object.keys(arguments));
}
You can use rest syntax to collect all the arguments into an array in acceptArguments
(which is preferred over using the arguments
variable), and then spread those arguments into the call of secondFunction
:
function acceptArguments(...args) {
secondFunction(...args);
}
function secondFunction(v1, v2, v3, v4) {
console.log(v1, v2, v3, v4);
}
acceptArguments(1, 2, 3, 4)