想终止JavaScript的forEach循环,可以使用for或

2024-01-18  本文已影响0人  FrankFang7

forEach的循环虽然能够终止,但不建议这么做。比如,抛出错误:

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

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

}

更好的建议是使用其它方法,比如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
  }
})
上一篇 下一篇

猜你喜欢

热点阅读