Consider the following Javascript code:
var a = [];
var f = function() {
    for (var i = 0; i < 3; i++) {
        a.push(function(){alert(i)});
    }
    for (var j = 0; j < 3; j++) {
        a[j]();
    }
};
The alerts print out '3' all three times. I want a different behaviour - in each iteration of the loop generate a function that prints the current value of i. I.e. 3 functions that print different indices.
Any ideas?
Create an anonymous function which accepts i as a parameter and returns that certain function:
for (var i = 0; i < 3; i++) {
    a.push((function(i) {
        return function() {
            alert(i);
        }
    })(i));
}
for (var j = 0; j < 3; j++) {
    a[j]();
}
Or do something similar: create an anonymous function which accepts i as a parameter to add the function to the array:
for (var i = 0; i < 3; i++) {
    (function(i) {
        a.push(function() {
            alert(i);
        });
    })(i);
}
for (var j = 0; j < 3; j++) {
    a[j]();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With