In everyday development, if the for loop says it is second, no one dares to call it first. In this article we’ll take a closer look at the use of the for loop in various scenarios.

1. Iterate through an ordinary array

When you need a break, continue, or return, use for(I =0… I++) and for… Of, but forEach cannot be used

Break and continue

let arr = [0.1.2.3.5]

for(let i = 0; i < arr.length; i ++) {
    if(arr[i] === 3) {
        break  / / 0 1 2
        // continue // 0 1 2 undefined 5
    }
    console.log(arr[i])
}
for(let item of arr) {
    if(item === 3) {
       break  / / 0 1 2
       // continue // 0 1 2 undefined 5
    }
    console.log(item)
}

arr.forEach((item, index, arr) = > {
    if(item === 3) {
        break  // 0 1 2 3 5
    }
    console.log(item)
})
Copy the code

Function to return

let arr = [0.1.2.3.5]
function f(arr) {
    arr.forEach((item, index, arr) = > {
        if(item === 3) {
            return  // 0 1 2 5
        }
    console.log(item)
    })
}
f(arr)

let arr = [0.1.2.3.5]
function f(arr) {
    for(let item of arr) {
        if(item === 3) {
            return  / / 0 1 2
        }
    console.log(item)
    }
}

f(arr)
Copy the code

The characteristics of summary

  1. for( i=0 … I++) traverses the index of the number group, for… Of iterates over the elements of an array. ForEach can iterate over indexes, elements, and arrays at the same time
  2. for( i=0 … I++) and for… Of can be broken by break and continue, or the loop can be broken by return. ForEeach is not affected by break and continue and cannot return the end function
  3. for( i=0 … I++) and for… The loop is still executed if the element is empty, and the loop is not executed if the element is empty

Summary of Usage Scenarios

  1. If return or break is required, select for… Of or for(I =0… i++ )
  2. ForEach or for(I =0… i++ )
  3. If index is required and return or break is required, select for(I =0… i++ )

2. The direction of this problem

let arr = [0.1.2.3.5]

for(let i = 0; i < arr.length; i ++) {
    console.log(this) // window
}

for(let item of arr) {
    console.log(this) // window
}

arr.forEach((item, index, arr) = > {
    console.log(this) // window
})

arr.forEach(function(item, index, arr) {
    console.log(this) // undefined
})
Copy the code

If forEach is a normal function, this cannot be initialized. Otherwise, this can be initialized.

Summary: Do not use this in forEach

3. Async /await

Use setTimeout to simulate asynchronously executing methods

passOrFailed (i) {
  return new Promise((resolve) = > {
    // Asynchronous operation
    setTimeout(() = > {
      console.log(`${i}Successful `)
      resolve()
    }, 1000)})},Copy the code

The test () function is called through the loop with the expectation that the first loop will complete before the next loop is executed

async test () {
  const arr = [1.2.3.4.5]
  for (let i = 0; i < arr.length; i++) {
    console.log(`${i}start`)
    await this.passOrFailed(i)
    console.log(`${i}end`)}}Copy the code

The desired outcome is this

// 0start
/ / 0 success
// 0end
// 1start
/ / success
// 1end
// ...
Copy the code

Let’s take a look at the complete code

3.1 the for (I = 0… i++ )

// a.vue
<script>
export default {
  methods: {
    passOrFailed (i) {
      return new Promise((resolve) = > {
        // Asynchronous operation
        setTimeout(() = > {
          console.log(`${i}Successful `)
          resolve()
        }, 1000)})},async test () {
      const arr = [1.2.3.4.5]
      for (let i = 0; i < arr.length; i++) {
        console.log(`${i}start`)
        await this.passOrFailed(i)
        console.log(`${i}end`)
      }
    }

  },

  mounted () {
    console.log('start!!! ')
    this.test().then(() = > { console.log('end!!! ') })
  }
}
</script>
Copy the code

3.2 the for… of

// a.vue
<script>
export default {
  data () {
    return{}},methods: {
    passOrFailed (i) {
      return new Promise((resolve) = > {
        // Asynchronous operation
        setTimeout(() = > {
          console.log(`${i}Successful `)
          resolve()
        }, 1000)})},async test () {
      const arr = [1.2.3.4.5]
      for (const item of arr) {
        console.log(`${item}start`)
        await this.passOrFailed(item)
        console.log(`${item}end`)
      }
    }

  },

  mounted () {
    console.log('start!!! ')
    this.test().then(() = > { console.log('end!!! ') })
  }
}
</script>
Copy the code

for( i=0 … I++) and for… The output of is the same

3.3 the forEach

If you change it to forEach like this, the compilation will report an error

// a.vue
async test () {
  const arr = [1.2.3.4.5]
  arr.forEach(item= > {
    console.log(`${item}start`)
    await this.passOrFailed(item)
    console.log(`${item}end`)})}Copy the code

We need to write it this way

// a.vue
<script>
export default {
  data () {
    return{}},methods: {
    passOrFailed (i) {
      return new Promise((resolve) = > {
        // Asynchronous operation
        setTimeout(() = > {
          console.log(`${i}Successful `)
          resolve()
        }, 1000)
      })
    },

    test () {
      const arr = [1.2.3.4.5]
      arr.forEach(async item => {
        console.log(`${item}start`)
        await this.passOrFailed(item)
        console.log(`${item}end`)
      })
    }
  },

  mounted () {
    console.log('start!!! ')
    this.test()
    console.log('end!!! ')
  }
}
</script>
Copy the code

The result is not what we logically expect

So try not to use forEach when it comes to asynchronous operations

4. To summarize

The usage of the for loop in different scenarios is summarized below

We see the original for(I =0… I++) is used in all scenarios, but the amount of code will be relatively more, forEach to write up the amount of code is less, but also more intuitive, but the use of limitations are relatively large, note that not all scenarios can be used oh. Use different loops for different scenarios.

If you think the article is useful to you, just click on the “like” and go, pen core ~