跳出循環(huán)的遍歷

  1. map不能跳出循環(huán),
  2. forEach跳出本次循環(huán)
    使用return終止本次循環(huán),執(zhí)行下一次循環(huán)
let arr = [1, 2, 3];
arr.forEach((item, index) => {
    if(item === 2) {
        console.log('中止本次循環(huán),繼續(xù)執(zhí)行下一次循環(huán)')
        return false;
    }
    console.log(index)
})
console.log('結(jié)束')
  1. forEach終止循環(huán)
    因為forEach無法通過正常流程結(jié)束循環(huán),可以通過拋出異常的方式實現(xiàn)終止循環(huán)
let arr = [1, 2, 3];
try {
    arr.forEach((item, index) => {
        if(item === 2) {
            throw new Error('End')
        }
        console.log(index)
    })
} catch(e) {
    if(e.message === 'End') throw e;
}

下表是JS中常用的實現(xiàn)循環(huán)遍歷的方法的跳出/結(jié)束遍歷的辦法:

方法 break continue return/return false return true
for 結(jié)束循環(huán) 跳出本次循環(huán) 不合法 不合法
forEach 不合法 不合法 跳出本次循環(huán) 跳出本次循環(huán)
for...in 結(jié)束循環(huán) 跳出本次循環(huán) 不合法 不合法
Array.map() 不合法 不合法 跳出本次循環(huán) 跳出本次循環(huán)
Array.some() 不合法 不合法 跳出本次循環(huán) 結(jié)束循序
Array.every() 不合法 不合法 結(jié)束循環(huán) 跳出本次循環(huán)
Array.filter() 不合法 不合法 跳出本次循環(huán) 跳出本次循環(huán)

參考鏈接
JS中如何跳出循環(huán)/結(jié)束遍歷

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容