1第一种抛出错误
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) {

}

我在网上查阅了很多一般都是以上这种抛出错误的方法来终止循环

第二种

let arr = [1, 2, 3, 4, 5]
        arr.forEach(item => {
            if (item > 2) {
                arr.length = 0
            }
            console.log(item);
        })  

 运行结果如下

 

但是这样会影响到原数组,但是也实现了我们的目的

结合这种方式还有以下方法

 思路也是跟方法二一样

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

array.forEach((it, i) => {
  if (it >= 0) {
    console.log(it)
    // Notice the sinful line of code
    array.splice(i + 1, array.length - i)
  }
})

虽然这种做法都不对,但是也能解决那些面试官的一些刁难

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐