kuoluozq

发现foreach时使用break或return无法跳出循环。经过查阅资料,发现两种方法可以跳出循环,在此记录

方法一:使用try{...}catch(e){...}

try{
    var array = ["first","second","third","fourth"];
    array.forEach(function(item,index){
	if(item == "third"){
		var a = aaaa;// first second 后就报错,就跳出循环了
		throw new Error("ending");//报错,就跳出循环
	}else{
		console.log(item);
	}
    })
}catch(e){
	if(e.message == "ending"){
		console.log("结束了") ;
	}else{
		console.log(e.message);
	}
}

方法二:使用arr.some()或者arr.every()替代

some()当内部return true时跳出整个循环:

 

var arr = [1,2,3,4,5];
var num = 3;
arr.some(function(v){
  if(v == num) {
	return true;
  }
  console.log(v);
});

 

every()当内部return false时跳出整个循环

var arr = [1,2,3,4,5];
var num = 3;
arr.every(function(v){
	if(v == num) {
		return false;
	}else{
		console.log(v);
		return true;
	}
});

  

 

分类:

技术点:

相关文章:

  • 2021-08-10
  • 2021-11-23
  • 2021-11-23
  • 2021-12-02
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2021-05-15
  • 2021-12-02
  • 2022-12-23
  • 2021-12-12
  • 2021-11-23
相关资源
相似解决方案