Possible Duplicate:
Javascript infamous Loop problem?
I have the following:
function test(a,b,c){
console.log(a+b+c);
}
for (var i=0; i < array.length; i++){
steps.push(
function(){ test(array[i].something, array[i].wow, i);}
);
I want to store functions with several parameters, and bind them to buttons later when the DOM is loaded
for (var i=0; i<steps.length; i++){
$('#mydiv li a').eq(i).click(steps[i]);
}
It’s not really working since steps[i] contains do(array[i].something, array[i].wow, i); instead of do(‘bob’, ‘john’, 1) for example
I have tried using the .apply javascript function but it will execute in the loop, instead of storing them
Closures can help you here. Here’s one solution to the first bit of code:
There’s no “block scope” in Javascript, just function scope. With your code, each function you pushed into the
stepsarray had a reference to the last value ofi, not the one it had when the function was pushed intosteps. Invoking an immediately executing function enables the pushed function to have a value forithat doesn’t change, because a closure is being created. And this closure has a value forithat is independent of the loop’s value fori, which will be whatever is the last index ofarray.