The function always results in the same number

I have a function at the bottom that always results in me 5. I can see that the inner function is executed in global context

, so the result is always 5.

I tried to wrap the whole loop inside the closure so that it creates a new scope until it fires.

var myAlerts = [];

for (var i = 0; i < 5; i++) {
    myAlerts.push(
        function inner() {
            alert(i);
        }
    );
}

myAlerts[0](); // 5
myAlerts[1](); // 5
myAlerts[2](); // 5
myAlerts[3](); // 5
myAlerts[4](); // 5

      

Can anyone tell me how to fix this problem?

+3


source to share


2 answers


Try to close:



for (var i = 0; i < 5; i++) {
    (function(i){
      myAlerts.push(
        function inner() {
            alert(i);
        }
      );
    })(i);
}

      

+3


source


Wrapping a function in a closure works:



var myAlerts = [];

for (var i = 0; i < 5; i++) {
  myAlerts.push((function(i) {
    return function inner() {
      alert(i);
    }
  })(i));
}

      

+1


source







All Articles