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

标签 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

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

最佳答案

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

关于javascript - 将可变长度数组传递给函数 Node JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25409431/

相关文章:

javascript - scrollTop 动画导致屏幕白色闪烁

javascript - 如何在JS中使用带有Promise结果的postMessage

javascript - NodeJS/Express app.use 顺序和用法

javascript - 为所有以特定字符串开头的变量赋值

java - 将数字保存到循环JAVA中的变量

php - 谷歌地图不显示

javascript - 如何在 JavaScript 中从 html 引用 iframe

node.js - 不知道如何使用 redux 表单发布,无法将状态映射到 PostNew

java - 在方法中声明 java 变量

javascript - 从 ajax 响应对象中多次替换一个词?