0

I'm using a single structure dynamically for many function as shown below:

Parent[funcName](data, function(err) {
   // further operations
});

The variable "data" in the function have 0, 1, 2 or 3 as per the function requirement. It works fine when single argument is passed in "data" but if more than 1, it shows error - "more argument are expected".

So how can I pass multiple arguments by using single variable? Is there any work around?

2
  • Pass an object. Commented Mar 7, 2018 at 10:47
  • pass data as an array Commented Mar 7, 2018 at 10:47

2 Answers 2

4

You can use the spread operator

Parent[funcName](...data, function(err) {
   // further operations
});

where data is the array of all the parameters you have passed.

Sign up to request clarification or add additional context in comments.

1 Comment

You could use the above syntax (rest parameters) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… but is not supported in Edge or IE
1

Just make use of the arguments object:

function myFunction() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

or this way:

function foo(...args) {
  return args;
}
foo(1, 2, 3); // [1,2,3]

greetings

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.