1、forEach跳出本次循環
可使用return語句跳出本次循環,執行下一次循環
var arr = [1,2,3,4,5,6] arr.forEach((item) => { if (item === 3) { return } console.log(item) })
將輸出 1 2 4 5 6,3不會輸出
2、forEach終止循環
forEach無法通過正常流程(如break)終止循環,但可通過拋出異常的方式實現終止循環
var arr = [1,2,3,4,5,6] try{ arr.forEach((item) => { if (item === 3) { throw new Error('End Loop') } console.log(item) }) } catch (e) { if(e.message === 'End Loop') throw e }
將只輸出 1 2
注意:在catch語句塊中加了if(e.message === 'End Loop') throw e
這句代碼會在控制台報一個錯誤,這個錯誤是try語句塊中拋出的,如下:
new_file.html:24 Uncaught Error: End Loop at new_file.html:24 at Array.forEach () at new_file.html:22
如果不想看到這個報錯,將if(e.message === 'End Loop') throw e
這一句刪除就行
原文鏈接:https://blog.csdn.net/daoxiaofei/article/details/108690589