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
- Block-level scopes are identified by {}, and the for loop should generate ten {} subblock scopes
- each subblock {} is associated with the corresponding I, that is, the I value of each loop Should the
- let be placed inside the for statement and outside the for statement outside the ten {} subblocks?
what is my mistake?