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;  
             }//可以跳出来

posted @ 2018-01-27 16:57  豆园子  阅读(20230)  评论(0)    收藏  举报