JavaScript——forEach跳出循环

想要在满足指定条件的时候跳出forEach循环

但是在打包的时候出错如下:


查阅相关资料,发现无法终止forEach遍历,跳出循环


然而 for循环

可以通过 return和break跳出循环

所以改用for循环,成功得到想要的效果


扩展:

for循环如果是多层循环 可以将循环命名,跳出指定的循环。

  1. first: //需要将循环命名
  2. for( var i= 0;i< 10;i++){
  3. for( var j= 0;j< 5;j++){
  4. if(i== 3 && j== 4){
  5. break first; //跳出循环first
  6. }
  7. }
  8. }

forEach 如果要提前终止

需要将forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止:

  1. var myerror = null;
  2. try{
  3. arr.forEach( function(el,index){
  4. if (el== 20) {
  5. console.log( "try中遇到20,能退出吗?"); //
  6. foreach.break= new Error( "StopIteration");
  7. } else{
  8. console.log(el);
  9. }
  10. });
  11. } catch(e){
  12. console.log(e.message);
  13. if(e.message=== "foreach is not defined") {
  14. console.log( "跳出来了?"); //
  15. return;
  16. } else throw e;
  17. } //可以跳出来

猜你喜欢

转载自blog.csdn.net/weixin_38213517/article/details/80912066