Array.forEach怎么跳出循环?

Array.forEach 怎么跳出循环?
forEach是不能通过break或者return跳出循环的,一般跳出循环的方式为抛出异常:

 try {
   let array = [1, 2, 3, 4]
   array.forEach((item, index) => {
     if (item === 3) {
       throw new Error('end')//报错,就跳出循环
     } else {
       console.log(item)
     }
   })
 } catch (e) {
 }

这种写法反而很麻烦。

解决方式

1. 使用 every 替代:

let array = [1, 2, 3, 4]
array.every((item, index) => {
  if (item === 3) {
    return true
  } else {
    console.log(item)
  }
})

2.自己写一个😁

//可跳出循环的数组遍历
Array.prototype.loop = function(cbk) {
  //判断当前数组是否为空
  if (this?.length) {
    for (let i = 0; i < this.length; i++) { let stop = cbk(this[i], i, this) //判断是否停止循环 if (stop) { break } } } } let array = [1, 2, 3, 4] array.loop ((item, index) => {
  if (item === 3) {
    return true
  } else {
    console.log(item)
  }
})

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系maynote@foxmail.com处理
码云笔记 » Array.forEach怎么跳出循环?

发表回复