【问题标题】:Passing Variable length array to function Node JS将可变长度数组传递给函数 Node JS
【发布时间】:2014-10-14 02:08:26
【问题描述】:

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

的变量中
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

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

【问题讨论】:

标签: javascript node.js variables


【解决方案1】:

看看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

【讨论】:

  • 谢谢!我会尽快接受。我知道我错过了一些简单的东西
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 2020-07-28
相关资源
最近更新 更多