user2512053
user2512053

Reputation: 79

Passing Variable length array to function Node JS

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 ?

Upvotes: 3

Views: 1158

Answers (1)

SamT
SamT

Reputation: 10620

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

Upvotes: 3

Related Questions