JavaScript的forEach、every、some方法

背景

有时在业务中,常常会碰到迭代数组时,满足某个条件之后就break掉的需求,但是Array对象的forEach函数并不支持continue, break关键字,最后无奈只能去写原生的for循环

  // 出现3之后停止循环
  const arr = [6, 4, 1, 3, 9, 5]

forEach

forEach函数会忽略返回值,并且无法中断循环,但是可以使用return跳过本次循环

  arr.forEach(item => {
    if (item === 3) {
      return
    }
    console.log(item)
  }) // 6 4 1 9 5

for

原生的for循环,可以使用关键字continue跳过本次循环和关键字break终止循环

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 3) {
      break
    }
    console.log(arr[i])
  } // 6 4 1

every

迭代时返回值为false时中断循环,可以使用return true跳过本次循环

  arr.every(item => {
    console.log(item)
    return item !== 3
  }) // 6 4 1 3

some

迭代时返回值为true时中断循环,可以使用return false跳过本次循环

  arr.some(item => {
    console.log(item)
    return item === 3
  }) // 6 4 1 3
posted @ 2022-07-20 10:09  Hyjax  阅读(227)  评论(0)    收藏  举报