当前位置:网站首页>The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

2022-07-06 21:10:00 viceen

for In circulation break And continue The difference between ——break- Complete end of cycle & continue- Terminate the loop

stay for In circulation break And continue The difference is as follows :

break Used to completely end a cycle , Jump out of the loop body and execute the statement after the loop ; and continue Is to skip the remaining statements in the current loop , Execute next cycle . In short, it's break Complete end of cycle ,continue Terminate the loop .

 Insert picture description here

1、continue- Terminate the loop

for (let i = 1; i < 5; i++) {
     
    if (i === 2) {
     
        continue; 
    } 
    console.log(i)  // 1 3 4
}

2、break- Complete end of cycle

for (let i = 1; i < 5; i++) {
     
    if (i === 2) {
     
        break; 
    } 
    console.log(i)  // 1
}
example
var methodInfoList = [
    {
    value:' Xiao Ming ',id:3},
    {
    value:' Xiaohong ',id:4},
    {
    value:' cockroach ',id:2},
]
var sign
for(var i=0, len = methodInfoList.length ; i< len ; i++){
    
    if(methodInfoList[i].value == ' Xiaohong ') {
    
        sign = 3
        console.log(798);
        break;
    }
    console.log(123,sign);
    if(methodInfoList[i].value == ' cockroach ') {
    
        console.log(852,sign);
        break;
    }
}

Print display order

123 undefined
798

3、 Comparison of different cycles

js in for Loops can be implemented in many ways , among forEach The way is incompatible break The grammatical .

3.1、 Use traditional for loop

This way supports continue, Also support break grammar

for(var i=0, len = methodInfoList.length ; i< len ; i++){
    
  if(methodInfoList[i].value == null || methodInfoList[i].value == "") {
    
	this.msgError(" The check method cannot enter a null value ");
	break;
  }
}
3.2、 Use for-in loop

adopt return true Implementation is not supported in this way continue and break The same function is to exit the current cycle ;
adopt return false Realization and break The same function is to exit the whole cycle

$.each(arr,function(index,oo){
    
    if(index == 2){
    
        return true;
    }
    if(index == 5){
    
        return false;
    }
})
3.3、 Use forEach loop

This way does not support continue and break, Nor does it support return The way ;

If you need to jump out of the loop, you can only throw exceptions

try {
    
 methodInfoList.forEach(element => {
    
	if (element.value == null || element.value == "") {
    
	  this.msgError(" The check method cannot enter a null value ");
	  throw new Error(" The check method cannot enter a null value ");
	}
 });
} catch(e){
    
 console.log(e.message);
}
原网站

版权声明
本文为[viceen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061250445007.html