Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript closure immediate evaluation [duplicate]

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?

like image 869
Yaniv Avatar asked Sep 12 '09 01:09

Yaniv


1 Answers

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]();
}
like image 180
strager Avatar answered Sep 24 '22 16:09

strager