vue-js-跳出forEach循环


发现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;
	}
});

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM