将可变长度数组传递给Node JS
有没有办法调用一个可变长度的插件函数。 我把用户input变成一个看起来像的variables
Uinput = [5,3,2];
现在我想打电话给我的插件基于这些数字,所以它会
addon.myaddon(5,3,2);
我也想扩展到n个input,所以如果我的variables的用户input成为
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
这似乎很简单,但它给我一些麻烦。 有小费吗 ?
看看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