12 - node access to file attributes - using a self-closure function call to solve the problem of lost i

The role of closure: Save Variable

A, i lost case

var arr = [ 'node', 'shock', 'mysql']

for(var i=0;i<arr.length;i++){  
  setTimeout(()=>{
    console.log(arr[i])  
  },1000)
}

 

Second, the solution

Use closures: 

for(var i=0;i<arr.length;i++){
  ((i)=>{
    setTimeout(()=>{
      console.log(arr[i])
    },1000)
  })(i)
}

Guess you like

Origin www.cnblogs.com/500m/p/10936093.html