First, let’s look at two examples. Here are some examples:
Example 1:
Example 1 code
for(var i=0; i<10; I++) {setTimeout (() = > {the console. The log (I + "random" + Math. The random ()})}Copy the code
Example 1 results are as follows:
Example 2:
Example 2 code
for(let i=0; i<10; I++) {setTimeout (() = > {the console. The log (I + "random" + Math. The random ()})}Copy the code
The result of example 2 is as follows:
Conclusion:
Huh? Why the difference?? What happened? At the beginning of learning JS when I do not understand, the back finally figured it out
First, the difference between var and let is well known. Var can promote variables while let cannot. Second, setTimeout is a timer that will execute an operation after several moments. It’s easy to explain based on the above knowledge.
Second, take a look at the following code:
Var can change an assigned variable, while let can only be declared once
Var has the function of variable promotion and is applied to the whole world. When I is 0 and I is 9, I will be changed, which will change the I equal to 0 into the I equal to 9, because setTimeout is asynchronous and will be executed after a while
Even if setTimeout executes the result after a while, I at the moment I =0 will still be 0 and will not become 9, because let cannot change the value of I at another moment!!