You can put the body of your loop in an anonymous function:
var a = [];
for(var i = 0; i < 3; i++) (function(i) {
a.push(function() { alert(i); });
})(i)
for(var j = 0; j < 3; j++) {
a[j]();
}
By creating that function and passing the loop's value of "i" as the argument, we are creating a new "i" variable inside the body of the loop that essentially hides the outer "i". The closure you push onto the array now sees the new variable, the value of which is set when the outer function function is called in the first loop. This might be clearer if we use a different name when we create the new variable... This does the same thing:
var a = [];
for(var i = 0; i < 3; i++) (function(iNew) {
a.push(function() { alert(iNew); });
})(i)
for(var j = 0; j < 3; j++) {
a[j]();
}
The value of "iNew" is assigned 0, then 1, then 2 because the function is called immediately by the loop.