0
点赞
收藏
分享

微信扫一扫

如何终止forEach循环?

一、序言

这个问题估计会难倒一部分同学。甚至会有人反问,forEach循环在JavaScript中能终止吗? 比如 ,我举个例子

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

array.forEach((it) => {
  if (it >= 0) {
    console.log(it)
    // 0 1 2 3
    return // or break
  }
})

从这个例子来看,好像不管是通过return还是break都无法终止forEach循环。 forEach相当于就是函数的执行,比如下面这段代码,即使func1执行了return语句,仍然会打印出2。

const func1 = () => {
  console.log(1)
  return
}

const func2 = () => {
  func1()
  console.log(2)
}

func2()

二、方法

01 抛出错误

当找到一个大于等于0的数字之后,return循环将终止执行,所以控制台只会输出数字0,代码如下:

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

try {
  array.forEach((it) => {
    if (it >= 0) {
      console.log(it) // 输出:0
      throw Error(`We've found the target element.`)
    }
  })
} catch (err) {
  
}

02. 将数组长度设置成0

我们也能通过将数组长度设置成0来终止forEach循环。代码如下

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

array.forEach((it) => {
  if (it >= 0) {
    console.log(it) // 输出:0
    array.length = 0
  }
})

03. 将数组元素移除

在日常工作中,一般是不会出现一种情况是让你终止forEach循环的,如果有终止的情况,可以使用for和some方法。

for

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

for (let i = 0, len = array.length; i < len; i++) {
  if (array[ i ] >= 0) {
    console.log(array[ i ])
    break
  }
}

some

const array = [ -3, -2, -1, 0, 1, 2, 3 ]

array.some((it, i) => {
  if (it >= 0) {
    console.log(it)
    return true
  }
})

举报

相关推荐

0 条评论