将可变长度数组传递给函数Node JS

时间:2014-08-20 16:03:28

标签: javascript node.js variables

有没有办法调用长度可变的插件函数。我将用户输入转换为看起来像

的变量
Uinput = [5,3,2]; 

现在我想根据这些数字拨打我的插件,这样就可以了

addon.myaddon(5,3,2);

我还希望将此扩展为n个输入,这样如果我的用户输入变量变为

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

然后将像

一样调用插件
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

这看起来很简单,但它给我带来了一些麻烦。有什么提示吗?

1 个答案:

答案 0 :(得分:2)

查看Function.prototype.apply

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

这相当于调用:

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

使用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
相关问题