美文网首页
JavaScript中 跳出(终止)forEach循环

JavaScript中 跳出(终止)forEach循环

作者: 臭臭的胡子先生 | 来源:发表于2021-02-13 15:09 被阅读0次

    JavaScript中 跳出(终止)forEach循环
    forEach()方法,不支持break和continue,但可以利用其他方式。

    跳出本次循环,需要用 return false or return true or return

    [1,2,3,4].forEach(function(item,i){
       if (item == 2){
           return false;
       }
       console.log(item);
    })
    

    输出结果


    image.png

    跳出整个forEach循环,可以通过抛出异常的方式实现终止整个循环

    try {
        // 执行到第3次,结束循环
        [1,2,3,4,5].forEach(function(item,index){
            if (item == 3) {
                throw new Error("End");
            }
            console.log(item); // 1,2
        });
    } catch(e) {
        if(e.message!="End") throw e;
    }
    

    输出结果


    image.png

    相关文章

      网友评论

          本文标题:JavaScript中 跳出(终止)forEach循环

          本文链接:https://www.haomeiwen.com/subject/ogsmtltx.html