(1)

Output what?


for (var i = 0; i < 5; i++) {

       console.log(i);

}

Copy the code

Answer: 0, 1, 2, 3, 4

(2)

Output what?


for (var i = 0; i < 5; i++) {

       setTimeout(function() {

              console.log(i);

       }, 100 * i);

}

Copy the code

Answer: 5. 5. 5

(3)

Output what?


for (let i = 0; i < 5; i++) {

       setTimeout(function() {

              console.log(i);

       }, 100 * i);

}

Copy the code

Answer: 0, 1, 2, 3, 4

(4)

Output what?


for (var i = 0; i < 5; i++) {

       requestAnimationFrame(() = > console.log(i));

}

Copy the code

Answer: 5. 5. 5

(5)

Output what?


for (let i = 0; i < 5; i++) {

       requestAnimationFrame(() = > console.log(i));

}

Copy the code

Answer: 0, 1, 2, 3, 4

parsing

(1) Output 0-4 must be no problem, is normal output

(3) (5) Output 0-4

Variables declared with the let (and const) keyword are block-scoped (a block is anything between {}). During each iteration, I is created as a new value, and each value exists in the block-level scope within the loop.

(2) (4) Output 55555

The event execution mechanism in JavaScript, setTimeout and requestAnimationFram are macro task queues. When the function is actually executed, the loop is complete. The I declared by the var keyword is global. During the loop, we increment the value of I by 1 each time we use the unary operator ++. So when setTimeout or requestAnimationFram is called, I is already assigned 3.

 

The solution

Change the scope of I.

We can write a function directly like this:


var f = function(i) {

       setTimeout(function() {

              console.log(i)

       }, 100 * i)

}

 

for (var i = 0; i < 5; i++) {

       f(i)

}

 

function foo(i) {

       requestAnimationFrame(() = > console.log(i))

}

for (var i = 0; i < 5; i++) {

       foo(i)

}

Copy the code

It can also be written as an anonymous function calling itself.


for (var i = 0; i < 5; i++) {

       (function(i) {

              requestAnimationFrame(() = > console.log(i))

       })(i)

}

 

Copy the code