I fixed a BUG today. The forEach loop stops when a certain condition is satisfied. Add return false to fix ~ but the code still continues to loop. Here’s my face:

This, of course, interrupts the program and computationally jumps out. Strictly speaking, map forEach itself is an iterative behavior that does not support jumps.

##1. Use a try catch to exit the forEach loop

Try {var array = [1,2,3,4,5,6]; ForEach ((value)=>{console.log()"value---->",value);
	   if(value > 3){
		 throw new Error("Throw exception out")}}); } catch(e) { console.log(e) };Copy the code

I wanted to keep track of this anyway — think about complementing other loops

##2. Break out of the for loop (no return method)

  • Break breaks all loops
for(var i=1; i<=10; i++) {if(I ==8) {// =8break; 
    } 
  console.log(i) 
}
Copy the code
  • Continue Jumps out of the current loop and enters a new loop
for(var i=1; i<=10; i++) {if(I ==8) {// =8continue; 
    } 
  console.log(i) 
}
Copy the code

##2.1. Break out of the for in loop (using break)

letArr = [6]for (let i in  arr){
	if(i > 3) {
		break
	}
	console.log(arr[i]) //1 2 3 4
}

Copy the code

Every returns false to break out of the loop. But inside the loop you still have to say return true to keep it going or you just do it once

When internal / / every ()return falseJump out of the looplet list = [1, 2, 3, 4, 5];
list.every((value, index) => {
    if(value > 3){
        console.log(value)
        return false; 
    }else{
        console.log(value)
        return true; // Of course, if you don't write this line, she will pop out as wellreturn trueIn order to get him into the next ghost.Copy the code

##4. Some Exits the entire loop when an internal return is true. If return false breaks this loop, it is similar to the for break and continue methods above

let list3 = [1, 2, 3, 4, 5];
    list3.some((value, index) => {
        if(value === 3){
            return true; / / when the internalreturn true} console.log(value)// 1 2});Copy the code

##5. In ES6, for of breaks the loop

letArr = [1, 2, 3, 4, 5]for (val of arr) {
if(val > 3 ){
	break;
}
console.log("val===>",val) //1 23
}
Copy the code

Let me write it down here. There e are so many details of the method used every day. They need to study hard ~ choose the right way to deal with the needs ~ their boring write small procedures welcome bug