[Interview question - print results] for (var i = 0; i < 2; i++) { setTimeout(function () { console.log(i) }, 0) } for (var

Say the following print result

for (var i = 0; i < 2; i++) {
    
    
  setTimeout(function () {
    
     console.log(i) }, 0)
}
for (var i = 0; i < 2; i++) {
    
    
  (function (i) {
    
    
    setTimeout(function () {
    
     console.log(i) }, 0)
  }(i))
}

The output of the first loop will be two 2's. This is because in the first loop, the setTimeout function will create two asynchronous tasks, but these two tasks will not be executed until the end of the loop and share the same variable i. When the asynchronous task is executed, the loop has ended, and the value of i has become 2, so the output result is two 2s.
注意: If i is declared with var in the for loop, i can be accessed globally. This is because the variable declared by var has function-level scope, not block-level scope. If you don't want to access it externally, just use let.

for (var i = 0; i < 2; i++) {
    
    
  setTimeout(function () {
    
     console.log(i) }, 0)
}
console.log(i)  // 2

In the second loop, the immediate execution function is used to pass the current i value into setTimeout, so that each loop will create a new scope and pass in the current i value, so that each setTimeout Has its own variable i. So the output will be 0 and 1.

Guess you like

Origin blog.csdn.net/owo_ovo/article/details/135253383