如何动态使用for循环,将具有不同参数的函数推送到数组中
How can I dynamically using for loop, push functions with different arguments to an array?
当前我正在尝试使用Node.JS 并行运行具有不同参数的相同函数
为此,我使用Async.js,并且我正在努力将函数推送到数组中。问题是这些函数是用相同的参数执行的。这就是我所拥有的:
var async = require("async");
var array = [];
var x = [1,2,3,4];
// This portion of code works perfect and the arguments are passed perfectly
// The results that i am getting are: [100, 200, 300, 400]
array.push(function(callback){ callback(null,calculate(x[0]))});
array.push(function(callback){ callback(null,calculate(x[1]))});
array.push(function(callback){ callback(null,calculate(x[2]))});
array.push(function(callback){ callback(null,calculate(x[3]))});
// This portion of code does not work and I dont know why ...
// The results that i am getting are: [400, 400, 400, 400]
// Obviusly the function is receiving the same argument a=4 everytime is called
for (i=0;i<3;i++){
array.push(function(callback){ callback(null,calculate(x[i]))});
}
async.parallel(array,function(err,result){
if (err) {
console.log(err);
return;
}
console.log("Results are: " + result);
});
function calculate(a) {
return a*100
}
知道怎么了吗?感谢
试试这个,这是一个关闭的问题
for (i=0;i<3;i++){
(function(i){
array.push(function(callback){ callback(null,calculate(x[i]))});
})(i)
}
let
就是您所需要的。
'use strict';
for (let i=0;i<3;i++){
array.push(function(callback){ callback(null,calculate(x[i]))});
}
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 函数未将值作为参数传递
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 为什么不'我们在javascript中使用函数参数的数据类型
- 你好,这是测试用例,我必须在函数中传递n个参数
- JavaScript - 多参数函数,它是多个图像库的字符串
- 如何从两个参数函数返回随机整数
- 以无点风格在Ramda中编写一个无参数函数
- JS:将单参数函数转换为可链接函数
- 正则表达式类似于Javascript中的参数函数
- 将 $' 值传递给替换的关联参数函数
- "这个“;在参数函数中
- 如何向jquery插件发送参数函数
- 将参数函数Node.js从一个js传递到另一个js
- 如何在javascript参数函数中传递PHP post方法字符串
- 装饰 Javascript Promise.then 以便参数函数接收附加参数
- 正在分析setInterval ID'是的's参数函数
- 如何根据一个参数函数计算年龄
- 对象参数/函数和/或三元运算符混淆