6

forEach跳出循环体

 3 years ago
source link: https://segmentfault.com/a/1190000038854657
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在forEach中,不能使用 continue 和 break ,可以使用 return 或 return false 跳出循环,效果与 for 中 continue 一样。注意该方法无法一次结束所有循环。

跳出本次循环

forEach 跳出本次循环,使用return

    [1,2,3,4,5].forEach(function(item,index){
        if(item == 3){
            return
        }
        console.log(3)// item == 3时,执行不到该部分,结束本次循环
    })

跳出整个循环

forEach 跳出整个循环,需要抛出异常

try {
    [1,2,3,4,5].forEach(function(item,index){
        if(item == 3){
            thorw new Error(); //结束整体循环
        }
    })
} catch(e) {

}

跳出嵌套循环

forEach 跳出嵌套循环

try {
    ["a","b","c"].forEach(function(item,index){

        try {
            [1,2,3,4,5].forEach(function(item,index){
                if(item == 3){
                    thorw new Error(); //结束整体循环
                }
            })
        } finally{}//try不能单独存在

        <!--catch(e) {-->
            //内层的catch不能存在,不然会捕获异常,只结束内层forEach
        <!--}-->

    })
} catch(e) { //在最外层捕获异常,可结束嵌套循环

}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK