如何优雅的跳出 for 循环

需求

如何做到优雅的跳出 for 循环

分析

循环遍历一般有以下几种

1. 普通for循环

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

在这里插入图片描述

2. for…in循环

属历史遗留,用于遍历对象的属性(数组的索引值也算属性)。
但有一个缺点:如果手动向数组添加成员属性,则:
虽然数组的length不变,但用for…in遍历数组会遍历到那些新定义的属性。

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

在这里插入图片描述

3. for…of循环(ES6)

for…of循环修复了for…in存在的问题,他只遍历属于对象本身的属性值。
且这个对象必须是iterable可被迭代的。如Array, Map, Set。

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

在这里插入图片描述

4. forEach(callbackFn, ?thisArg)方法(ES5.1)

  • iterable可被迭代的对象都有forEach(callbackFn, ?thisArg)。
  • 而Array, Map, Set对象都是可被迭代的。
  • forEach()接收一个回调函数callbackFn,每次迭代都回调该函数。
  • 回调函数的参数列表为(value, key, iterable),依次是(值, 键, 可迭代的对象本身)。
    iterable.forEach(function(value, key, iterable) {
          
          
      console.log(key, value, iterable);
    });
    

在这里插入图片描述

源码

1. 终止 普通 for 循环

break 跳出循环

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

2. 终止 forEach

2.1 forEach 可以跳出本次循环,执行下一次循环

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

将输出 1 2 4 5 6,3不会输出

2.2 forEach终止循环

forEach无法通过正常流程(如break)终止循环,但可通过抛出异常的方式实现终止循环

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
}

将只输出 1 2

猜你喜欢

转载自blog.csdn.net/qq_53810245/article/details/131583484
今日推荐