How the forEach method breaks out of the loop and the for method breaks out of the loop

1. The forEach method jumps out of the loop ---- jumps out of the loop by throwing an exception and skips the current loop through return

var arr=[1,3,5,7,9];
    var id = 5;
    try{
      arr.forEach(function(curItem,i){
        if(curItem===1)return;
        console.log(curItem);
        if(curItem===id){
          throw Error();
        }
      })
    }catch(e){
      console.log(e)
    }

 

2. The for method jumps out of the loop -----break jumps out of the loop continue jumps out of the current loop

 var arr=[1,3,5,7,9];
    var id = 5;
    for(var i=0;i<arr.length;i++){
      if(arr[i]===1)continue;
      console.log(arr[i])
      if(arr[i]===id){
        break;
      }
    }

If the print results are 3 and 5, but the rest are not printed, it means that the loop is jumped out when reaching 5, and the current loop is skipped by 1

Tips: The difference between for and forEach


1. forEach() cannot use the keywords break and continue. It can achieve the effect of break by throwing an exception, and the effect of continue can be directly used return

2. The advantage of forEach is that it passes in a function, so it forms a scope, and the variables defined inside it will not pollute the global variables like the for loop

3. forEach() itself cannot jump out of the loop, it must traverse all the data to end
 

Guess you like

Origin blog.csdn.net/weixin_43923808/article/details/131770222