foreach跳出本次/當前循環與終止循環方法


foreach()循環中,想要在循環的時候,當滿足某個條件時,想要跳出本次循環繼續執行下次循環,或者滿足某個條件的時候,終止foreach()循環,分別會用到:continue 與 break
PHP:

 foreach($arras $key => $value){  
        if($value=='b'){
            $html.= $value;  
            continue;// 當 $value為b時,跳出本次循環 
        }  
        if($value=='c'){  
            $html.= $value;  
            break;// 當 $value為c時,終止循環 
        }
    }
    echo$html; // 輸出: abc 

JavaScript:

var myerror = null;  
             try{  
                 arr.forEach(function(el,index){  
                     if (el==20) {  
                         console.log("try中遇到20,能退出嗎?");// 
                         foreach.break=new Error("StopIteration");  
                     }else{  
                         console.log(el);  
                     }  
                 });  
             }catch(e){  
                 console.log(e.message);  
                 if(e.message==="foreach is not defined") {  
                     console.log("跳出來了?");// 
                     return;  
                 }else throw e;  
             }//可以跳出來


免責聲明!

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



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