JS in the for loop variable scope (reprint)

Reprinted Source: https://www.cnblogs.com/zhus/p/6513741.html

 

A = var [];
for (var I = 0; I <10; I ++) {
var Q = I;
A [I] = function () {the console.log (Q)}
}
A [0] ()

wherein, Since the for-loop is not a function of the body, the loop variable q and I for the body of the function defined in scope of the for loop is located, and a peer,
I and q = i ++ is not redefined variables, just repeat the assignment, the final end of cycle, i = 10, q = 9 ;
since the function () {console.log (q) } is not executed immediately, so there has been a q memory references stored, eventually all the a [i] () are 9 output
, however, let the new command in the es6 declare variables, usage and the like var, but let the declared variable, the only effect let command block is located, for the loop counter is very suitable let command
var a = [];
for (the let I = 0; I <10; I ++) {
Ley Q = I;
A [I] = function () {the console.log (Q)}
}
A [. 6] () here will // variable output 6 let statement is only valid in the block-level scope, so here i only have effect in the current round of cycles each of i in fact a new variable

Guess you like

Origin www.cnblogs.com/hao-1234-1234/p/12180728.html