Javascript - add more parameters to a callback function [duplicate]
I'm calling an async function that needs a callback function as parameters.
Here is the javascript code:
for(i in array)
{
var item = array[i];
functionToCall(item[i][1], 50, function(a, b)
{
alert(a + b);
});
}
I cannot edit functionToCall function. What I want to do is using the "item" variable in the callback function like this.
for(i in array)
{
var item = array[i];
functionToCall(item[i][1], 50, function(a, b, c)
{
alert(a + b + c);
}, item);
}
But this code doesn't work properly. I cannot just use "item" inside the function because 开发者_StackOverflow中文版it is always using the last item in array.
So how can I do that?
You can use item
inside the function, but you need to "capture" it so that you don't end up using the last element of the array everytime.
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);
}
It's a bad idea to use for..in
to iterate arrays. Instead use .forEach()
and a lot of your problems just go away:
array.forEach(function(item)
{
functionToCall(item[1], 50, function(a, b)
{
alert(a + b + item[1]);
});
}
To use .forEach()
in older browsers, see this.
I would try something like 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();
}
精彩评论