JS中forEach跳出本次循環和終止循環


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM