1. Explain why the following code prints six 6’s
let i = 0
for(i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
SetTimeout means to wait for the value of “I” to be typed, so the system will execute the loop first, and then print “I” when the loop is finished
2. Write ways to make the above code print 0, 1, 2, 3, 4, 5
for(let i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code