6

三种在JavaScript中终止forEach循环的方式

 8 months ago
source link: https://www.51cto.com/article/777004.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

三种在JavaScript中终止forEach循环的方式

作者:佚名 2023-12-19 16:43:01

面试官:你能停止 JavaScript 中的 forEach 循环吗?这是我在面试中曾被问到的一个问题,我当初的回答是:“不,我不能这样做。”

面试官:你能停止 JavaScript 中的 forEach 循环吗?这是我在面试中曾被问到的一个问题,我当初的回答是:“不,我不能这样做。”

32a473f787658ece63e024987b7244a021d849.jpg

不幸的是,我的回答导致面试官突然结束了面试,对的,是突然结束的!

我对结果感到沮丧,问面试官:“为什么?实际上可以停止 JavaScript 中的 forEach 循环吗?”

在面试官回答之前,我花了一些时间解释我对为什么我们不能直接停止 JavaScript 中的 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()

二、终止方法

然而,我能想到三种方式可以终止forEach循环。

1. 抛出错误

当找到一个大于等于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) {


}

2. 将数组长度设置成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
  }
})

3. 将数组元素移除

当满足条件时,使用splice方法将数组内元素移除,也能终止forEach循环。代码如下:

const array = [ -3, -2, -1, 0, 1, 2, 3 ]
 
array.forEach((it, i) => {
  if (it >= 0) {
    console.log(it) // 输出:0
    array.splice(i + 1, array.length - i)
  }
})

建议使用for和some

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

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
  }
}
const array = [ -3, -2, -1, 0, 1, 2, 3 ]
 
array.some((it, i) => {
  if (it >= 0) {
    console.log(it)
    return true
  }
})

最后,3种关于在JavaScript中终止forEach循环的方法就先介绍到这里了,希望对你有所帮助,感谢你的阅读,编程快乐!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK