-2

I need to call a function in javaScript

service.call(row.operation, args.arg1, args.arg2, args.arg3,...,argN )

And I have array of the parameters of random length. How to pass this array to a function as a parameter list?

UPDATE

I can't change call method signature. 'Call' method is custom, not standard.

avalon
  • 2,231
  • 3
  • 24
  • 49
  • Make it an array – ProEvilz Nov 15 '17 at 12:29
  • @ProEvilz — Make what an array? They said they already have an array. – Quentin Nov 15 '17 at 12:29
  • @Quentin `args.arg1, args.arg2, args.arg3` isn't an array. The way I understand it is that ^ that is an example of the dynamic args. Simply put an array and then it can hold an untold amount of `args.arg1, args.arg2, args.arg3` – ProEvilz Nov 15 '17 at 13:33
  • @ProEvilz — That code example is how they are calling the function currently. They said they have the parameters in an array. The question is how to pass that array of parameters to the function (which isn't expecting a single argument that is an array, but which does expect separate arguments) – Quentin Nov 15 '17 at 14:38

2 Answers2

0

You can use the spread operator, it is perfectly suited for a varying number of parameters. Please have a look at this detailed description:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Rob
  • 11,492
  • 14
  • 59
  • 94
-3

Use apply instead of call. It expects the parameters in the form of an array.

var args = [ args.arg1, args.arg2, args.arg3 ];
service.apply(row.operation, args);

Re edit:

I can't change call method signature. 'Call' method is custom, not standard.

First: Buy a copy of JavaScript: The Definitive Guide (it is a very thick book) and use it to beat some sense into whoever named the call method on your service object.

Then … use apply to call the call method.

var args = [row.operation, args.arg1, args.arg2, args.arg3 ];
service.call.apply(service.call, args);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This is not my function and call is not a standard method. I can't change it's signature. – avalon Nov 15 '17 at 12:30
  • @avalon — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call — `call` is a standard method! – Quentin Nov 15 '17 at 12:31
  • @avalon — And if it is some weird function where `call` has been overridden, the answer is still to use `apply`: `service.call.apply(service.call, args)` – Quentin Nov 15 '17 at 12:34
  • Why do you have `row.operation` as the first argument? – Andy Nov 15 '17 at 12:38
  • @Andy — The first argument of `call` is the `this` value. The first argument of `apply` is the `this` value. When adapting the code to use `apply` to allow for a variable number of arguments defined by an array, the `this` argument is not changed. The value is therefore the same as the one used in the original code from the question. – Quentin Nov 15 '17 at 12:39