js中如何跳出forEach循环?

版权声明:本文为博主原创文章,欢迎转载,转载请标明出处。 https://blog.csdn.net/YeShenLiaoSuiFeng/article/details/81879855

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

forEach()使用三个参数调用该 函数:数组元素、元素的索引和数组本身。

注意: forEach() 对于空数组是不会执行回调函数的。

array.forEach(function(currentValue, index, arr), thisValue)。

回到本文的主题,js中forEach中一般是没办法终止跳出的。怎么实现退出?

var arr = ['a','b','c']

思路1   break

arr.forEach((item,index) => {
  if(item === 'b') break
  console.log(item)
})

// ==> Uncaught SyntaxError: Illegal break statement

执行后会报错。

思路2   return false

arr.forEach((item,index) => {
  if(item === 'b') return false
  console.log(item)
})

// ==> a, c

会跳出当前的遍历执行

思路3  try...catch 语句跳出异常

try {
  arr.forEach((item,index) => {
    if(item === 'b') throw new Error('exist')
    console.log(item)
  })
} catch (e) {
  if(e.message=='exist') throw e
} finally {
  console.log('done')
}

// a 按预期退出循环

// exist
// done

程序最后可以终止退出循环,所以使用try...catch 通过抛出异常的方式来终止程序继续执行是可行。

猜你喜欢

转载自blog.csdn.net/YeShenLiaoSuiFeng/article/details/81879855