1. Why does the following code print 6 6’s
Example 1:let i = 0
for(i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}Copy the code
SetTimeout () is asynchronous code that executes after synchronous code has finished executing. After the for loop completes, there are six console.log(I) tasks in the queue, and the scope is I = 6 (there is only one I, not the nearest rule), so it prints six sixes.
2. Method of printing 0, 1, 2, 3, 4, 5
Example 2:for(let i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}Copy the code
According to the ES6 standard, every time the for loop is executed, I is copied, so there will be six I after setTimeout(), and then print 0, 1, 2, 3, 4, 5.
3. Other methods of printing 0, 1, 2, 3, 4, 5
Example 3: Closureslet i
for(i = 0; i<6; i++){
!function(j){
setTimeout(() = >{
console.log(j)
},0)
}(i)
}
Copy the code
Fact 4: Array pushvar arr4 = [];
var n = 0;
for(var i = 0; i<6; i++) { n+=1;
arr4.push(n-1)}console.log(arr4)
Copy the code
Example 5: UsesetTimeoutThe third argument to, pass in Ilet i
for(i = 0; i<6; i++){
setTimeout((value) = >{
console.log(value)
},0,i)
}
Copy the code
Example 6: UtilizationconstThe keywordlet i
for(i = 0; i<6; i++){
const x = i
setTimeout(() = >{
console.log(x)
})
}
Copy the code