1. Why does the following code type 6 sixes

1.1 code

let i = 0
for(i = 0; i<6; i++){
  setTimeout(() = >{
    console.log(i)
  },0)}Copy the code

1.2 the reason

  1. Because JS is single-threaded, single-threaded means that all tasks need to be queued. The second task is executed only after the first task is completed.
  2. The code executes the for loop and then console.log(I), but by the time I is done, it’s already 6, and it doesn’t change, so after a while it prints all 6

2. Write a way for the above code to print 0,1,2,3,4,5

2.1 code

for(let i = 0; i<6; i++){
  setTimeout(() = >{
    console.log(i)
  },0)}Copy the code

2.2 the results

3. Print 0,1,2,3,4,5 with forEach

3.1 code

let arr = [0.1.2.3.4.5]
arr.forEach(item= >console.log(item))
Copy the code

3.2 the results