How does ES6's let play a role in the classical problem of the for cycle?

question

while reviewing the block-level scope of ES6, I encountered the classic problem of for loop, that is,

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

how to make the output from 1 to 9, which is generally done using ES6,:

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

my misunderstanding

I think the above answer can also be written as:

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

output: 10? is not what you imagined? Why not 6?

my reason

  1. Block-level scopes are identified by {}, and the for loop should generate ten {} subblock scopes
  2. each subblock {} is associated with the corresponding I, that is, the I value of each loop
  3. Should the
  4. let be placed inside the for statement and outside the for statement outside the ten {} subblocks?

what is my mistake?

Apr.21,2021

the fault lies in the third point of the reason. The let is placed inside the for statement, and the scope is within each loop within the for; the scope is defined outside the for statement, and the scope is inside the outer {}.

in for let: the I of each loop is actually a new variable . The JavaScript engine remembers the value of the previous cycle. When initializing the variable I of this round, it is calculated on the basis of the previous cycle.


of for calculate a scope for each cycle, but not on the outside


thanks to @ ezmo and @ xialeistudio for their answers, this question was finally found on the site. https://codeshelper.com/a/11.
@ Yu mentioned that the let in the for loop is a specially defined part of the standard, and in fact the following code:

var funcs = [];
for (let i = 0; i < 3; iPP) {
    funcs[i] = function () {
        console.log(i);
    };
}
funcs[0](); // 0

can be broken down into:

// 
(let i = 0) {
    funcs[0] = function() {
        console.log(i)
    };
}

(let i = 1) {
    funcs[1] = function() {
        console.log(i)
    };
}

(let i = 2) {
    funcs[2] = function() {
        console.log(i)
    };
};

this is not consistent with "experience", which is the root cause of misunderstanding. From the perspective of C language, the variable definition in for is the same as the external definition of for, because the language itself is initialized only once at the location of the variable definition, but the let processing inside and outside the for in js has different internal mechanisms. @ ezmo's answer actually explains this situation, but I don't know whether there is a unique standard for let in for or in the clouds. Who would have thought that there is such a grammatical definition in a simple for?


   

can anyone answer why you got this result?

Menu