JS如何終止forEach循環


我們都知道for循環里要跳出整個循環是使用break,但在數組中用forEach循環如要退出整個循環呢?使用break會報錯,使用return也不能跳出循環。

使用break將會報錯:

    var arr = [1,2,3,4,5];
    var num = 3;
    arr.forEach(function(v){
       if(v == num) {
           break;
       }
       console.log(v);
    });

 

 使用return也不能跳出整個循環:

    var arr = [1,2,3,4,5];
      var num = 3;
    arr.forEach(function(v){
      if(v == num) {
        return;
      }
              console.log(v);
    });

 

 解決方法:

    1:使用try···catch捕獲異常實現:

       try{

            var array = [1,2,3,4,5];
            array.forEach(( item,index ) => {
                    if(item == 3){
                        // 執行完 1 2 之后就報錯,就跳出循環了
                   throw new Error("ending");//報錯,就跳出循環
                   }else{
                      console.log(item);
                    }
               })
    }catch(e){
            if(e.message == "ending"){
               console.log("結束了") ;
            }else{
                console.log(e.message);
            }
    }

 

    2:使用arr.some( )  或者  arr.every( ) 替代

      some()當內部return true時跳出整個循環:

        var arr = [1,2,3,4,5];

        var num = 3;

        arr.some( item =>{
             if( item == num ) {
               return true;
           }
           console.log( item );
        });
       every()當內部return false時跳出整個循環:

        var arr = [1,2,3,4,5];
        var num = 3;
        arr.every( item =>{
          if( item == num ) {
          return false;
        }else{
          console.log( item );
          return true;
        }
       });

 

 

 

 

 


免責聲明!

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



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