Javascript - 在回调函数中添加更多参数
问题描述:
我正在调用一个需要回调函数作为参数的异步函数。Javascript - 在回调函数中添加更多参数
下面是javascript代码:
for(i in array)
{
var item = array[i];
functionToCall(item[i][1], 50, function(a, b)
{
alert(a + b);
});
}
我不能编辑functionToCall功能。我想要做的就是像这样在回调函数中使用“item”变量。
for(i in array)
{
var item = array[i];
functionToCall(item[i][1], 50, function(a, b, c)
{
alert(a + b + c);
}, item);
}
但是这段代码无法正常工作。我不能只在函数内使用“item”,因为它总是使用数组中的最后一项。
那么我该怎么做呢?
答
您可以在函数内使用item
,但需要“捕获”它,以便每次最终都不要使用数组的最后一个元素。
for(var i = 0, l = array.length; i < l; ++i) { // better than for .. in
var item = array[i];
(function(item, i){
functionToCall(item[i][1], 50, function(a, b) // do you really re-index item with the same index?
{
alert(a + b);
});
})(item, i);
}
答
使用for..in
迭代数组是个坏主意。而是使用.forEach()
,有很多你的问题走开:
array.forEach(function(item)
{
functionToCall(item[1], 50, function(a, b)
{
alert(a + b + item[1]);
});
}
要在旧的浏览器使用.forEach()
,see this。
答
我会尝试这样的事:
function createExecutionCall(itemIndex, number, item)
{
return function() { functionToCall(itemIndex, number, function(a, b)
{
// Example, item should be contained within this closure then
alert(a + b + item);
});
}
for(i in array)
{
var item = array[i];
var call = createExecutionCall(item[i][1], 50, item);
call();
}
它比预期的要好,非常感谢! – Marm