JavaScript: Binding for the cycle and let var variables

Encounter a question:

for (var I = 0; I <2; I ++) { 
the setTimeout (function () {
the console.log (I);
}, 100)
} // Output results: 22

for(let i=0;i<2;i++){ setTimeout(function(){ console.log(i); },100) } // output is: 01

We start talking about the first for loop, setTImeout is executed asynchronously

Thus setTImeout in the asynchronous queue, synchronization wait queue (for loop) can be conducted after the completion of execution,

At this time, after the completion of the implementation of the synchronous queue i is 2, setTimeout executed, output 2

 

Then look for the second cycle, since i using the let-defined, let to block-level scope, but according to our normal understanding, the outcome should be the upper side

Looking at the Internet, explained as follows:

for circulating let, in fact it is re-bound to each loop iteration, the next step will be to ensure that the cycle after the end of the last iteration of the loop, re-assignment

It simply is let the for loop, each time will be needed to ensure that the next cycle after the completion of the loop body is executed (I was so understandable)

 

But also to find a similar example

was a = [];
for ( the i = 0 ; i < 10 ; i ++ ) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10

Since i is a global scope, the function can be obtained in i acquired, the output from the array of functions is 10 i;

There are a = [];
for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 6

 Where i is the block-level scope, only the current i in the current round miraculous cycle, are each time a new loop variable i, so the final value is taken 6

 

Guess you like

Origin www.cnblogs.com/kongbaifeiye/p/11931113.html