How to break out of the for loop gracefully

need

How to gracefully break out of the for loop

analyze

Cycle traversal generally has the following types

1. Normal for loop

for (i = 0; i < loopTimes; i++) {
    
    
  console.log(i);
}

insert image description here

2. for...in loop

It is a historical legacy and is used to traverse the properties of the object (the index value of the array is also considered a property).
But there is a disadvantage: if you manually add member attributes to the array, then:
although the length of the array remains unchanged, traversing the array with for...in will traverse to those newly defined attributes.

for (property in obj) {
    
    
  console.log(property, obj[property]);
}

insert image description here

3. for...of loop (ES6)

The for...of loop fixes the problem of for...in. It only traverses the property values ​​​​that belong to the object itself.
And this object must be iterable can be iterated. Such as Array, Map, Set.

for (element of iterable) {
    
    
  console.log(element);
}

insert image description here

4. forEach(callbackFn, ?thisArg) Method (ES5.1)

  • iterable objects that can be iterated have forEach(callbackFn, ?thisArg).
  • And Array, Map, Set objects can be iterated.
  • forEach() receives a callback function callbackFn, which is called back for each iteration.
  • The parameter list of the callback function is (value, key, iterable), followed by (value, key, iterable object itself).
    iterable.forEach(function(value, key, iterable) {
          
          
      console.log(key, value, iterable);
    });
    

insert image description here

source code

1. Terminate the normal for loop

break out of the loop

for(var j = 0; j < 3; j++) {
    
    
      if ( j === 1) {
    
    
          break ;      
      }  
  }   

2. Terminate forEach

2.1 forEach can jump out of this cycle and execute the next cycle

var arr = [1,2,3,4,5,6]
arr.forEach((item) => {
    
    
	if (item === 3) {
    
    
		return
	}
    console.log(item)
})

Will output 1 2 4 5 6, 3 will not output

2.2 forEach terminates the loop

forEach cannot terminate the loop through a normal process (such as break), but it can terminate the loop by throwing an exception

var arr = [1,2,3,4,5,6]
try{
    
    
  arr.forEach((item) => {
    
    
  	  if (item === 3) {
    
    
  		  throw new Error('End Loop')
  	  }
      console.log(item)
  })
} catch (e) {
    
    
    if(e.message === 'End Loop') throw e
}

will only output 1 2

Guess you like

Origin blog.csdn.net/qq_53810245/article/details/131583484