js中如何跳出forEach循环?

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 通过抛出异常的方式来终止程序继续执行是可行。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值