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抓紧创作!

微信微信 支付宝支付宝

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Array.forEach怎么跳出循环?

发表回复