3

Is there a way to call an addon function with a variable length. I take the user input into a variable that looks like

Uinput = [5,3,2]; 

Now i want to call my addon based on these numbers so it would be

addon.myaddon(5,3,2);

I also want to extend this to n inputs so if my variable of user inputs becomes

Uinput = [5,3,2,6,...,n];

then the addon will be called like

addon.myaddon(5,3,2,6,...,n);

addon.myaddon(Uinput) // will not seperate the inputs by commas are they are in the array variable, it treats the whole array as the input

This seems simple enough but it is giving me a bit of trouble. Any tips ?

SamT
  • 10,374
  • 2
  • 31
  • 39
user2512053
  • 79
  • 4
  • 12
  • possible duplicate of [Call function with multiple arguments](http://stackoverflow.com/questions/1881905/call-function-with-multiple-arguments) – Felix Kling Aug 20 '14 at 16:39

1 Answers1

3

Take a look at Function.prototype.apply

Uinput = [5,3,2,...,7]; // the last number in the array is in position 'n'
addon.myaddon.apply(null, Uinput);

This is equivalent to calling:

addon.myaddon(Uinput[0], Uinput[1], Uinput[2], ... , Uinput[n]);

Real example using Math.max:

// Basic example
Math.max(1,6,3,8,4,7,3); // returns 8

// Example with any amount of arguments in an array
var mySet = [1,6,3,8,4,7,3];
Math.max.apply(null, mySet); // returns 8
SamT
  • 10,374
  • 2
  • 31
  • 39