The problem of let declaring variables in ES6

read an article in ES6 today:

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

document says that in the above code, the variable I is declared by let, and the current I is only valid in this loop, so the I of each loop is actually a new variable, so the final output is 6.

but isn"t a [6] function () {console.log (i)}? When running a [6] (), since I is declared by let and is only valid in block-level scope, shouldn"t I print out undefined? How could it be six?

May.05,2021

for each loop generates a new scope, and I in fuction accesses I within this scope, which can be understood like this:

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

you can use babel to escape the source code look at:

clipboard.png


coincidentally, I happen to have written an article on this question. You can take a look at it.
. Although I thought it was very clear at that time, after reading it now, I felt that I couldn't understand it. But it still means
my previous analysis of this problem < / A >


I is declared in outer curly braces. So the curly braces inside also take effect, and vice versa, which can be simply understood as passing down the scope

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e50d08-450d3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e50d08-450d3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?