zoukankan      html  css  js  c++  java
  • js中forEach无法跳出循环?

    1.  forEach()

     

    forEach() 方法从头至尾遍历数组,为每个元素调用指定的函数。如上所述,传递的函数作为forEach()的第一个参数。然后forEach()使用三个参数调用该 函数:数组元素、元素的索引和数组本身。如果只关心数组元素的值,可以编写只有一个参数的函数——额外的参数将忽略:

    var data = [1,2,3,4,5];

    //要求和的数组

    // 计算数组元素的和值

    var sum = 0;                                        

    // 初始为0

    data.forEach(function(value){ sum += value; }); 

    // 将每个值累加到sum上

    sum                                                 

    // => 15

    // 每个数组元素的值自加1

    data.forEach(function(v,i, a){ a[i] = v + 1; });

    data                                                

    // => [2,3,4,5,6]

    注意,forEach()无法在所有元素都传递给调用的函数之前终止遍历。也就是说,没有像for循环中使用的相应的break语句。如果要提前终止,必须把forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止:

    function foreach(a,f,t){

        try { a.forEach(f,t); }

        catch(e){

            if(e === foreach.break)return;

            else throw e;

        }

    }

    foreach.break = new Error("StopIteration");

    转自: 《JavaScript权威指南(6版)》7.9.1 forEach()

     


    2.现在让我们来实践一下吧!!!是不是很兴奋?!是不是很激动?!!是不是迫不及待!!!

    Let's Go !!!

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6 </head>
     7 <body>
     8     <script type="text/javascript">
     9         
    10 
    11         function skipOutForeach(){
    12 
    13             //1.测试 return,return false是否能跳出循环
    14             var arr = [];
    15             arr = getArr(1,30);
    16             console.log(arr);
    17             arr.forEach(function(el,index){
    18                 if (el==20) {
    19                     console.log("遇到20,能退出吗?");//并不能
    20                     return;//return false;
    21                 }else{
    22                     console.log(el);
    23                 }
    24             });
    25 
    26             //2.使用异常的方式来跳出forEach循环---------------------------
    27             console.log("-------------------------------")
    28             var myerror = null;
    29             try{
    30                 arr.forEach(function(el,index){
    31                     if (el==20) {
    32                         console.log("try中遇到20,能退出吗?");//
    33                         foreach.break=new Error("StopIteration");
    34                     }else{
    35                         console.log(el);
    36                     }
    37                 });
    38             }catch(e){
    39                 console.log(e.message);
    40                 if(e.message==="foreach is not defined") {
    41                     console.log("跳出来了?");//
    42                     return;
    43                 }else throw e;
    44             }//可以跳出来,那么 我们可以重写foreach方法
    45             //-----------------------------
    46             console.log("aaa");
    47             
    48         }
    49 
    50         // skipOutForeach();
    51 
    52         //自定义foreach方法(往Array或String的prototype添加也可以)
    53         function fore7(arr,func){
    54             console.log(arr);
    55             for (var i = 0; i < arr.length; i++) {
    56                 var ret= func.call(this,arr[i],i);//回调函数
    57                 if(typeof ret !== "undefined"&&(ret==null||ret==false)) break;
    58             }
    59             
    60         }
    61 
    62         //自定义foreach,的用法
    63         fore7(getArr(1,30),function(a,i){
    64             console.log(i+':'+a);
    65             if (i==20) return false;//跳出循环
    66         })
    67 
    68 
    69 
    70 
    71 
    72 
    73 
    74 //返回min,max之间的数组成的数组,无序
    75         function getArr(min,max){
    76             if(typeof min!=='number'||typeof max !== 'number') return [];
    77             var arr = [];
    78             for (var i = min; i <= max; i++) {
    79                 if (arr.length<1) {
    80                     arr.push(i);
    81                 }else{
    82                     var len = arr.length;
    83                     var rIndex = Math.round(Math.random()*(len-1));
    84                     var temp = arr[rIndex];
    85                     arr[rIndex] = i;
    86                     arr.push(temp);
    87                 }
    88             }
    89             return arr;
    90         }
    91     </script>
    92 </body>
    93 </html>

       3.for循环

        return,break都可以跳出

      但是多重循环呢?

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

     

      4.附录:

     StackOverFlow: http://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach

     

  • 相关阅读:
    codeforces 455C 并查集
    poj 3501 Escape from Enemy Territory 预处理+二分+bfs
    POJ 2110 Mountain Walking 二分+bfs
    poj1637 Sightseeing tour 混合图欧拉回路判定
    ubuntu禁用super(win)键
    win10 ubuntu双系统安装后无法引导进入ubuntu
    python2限制函数传入的关键字参数
    python限制函数执行时间
    python classmethod 和 staticmethod的区别
    centos sendmail 启动慢
  • 原文地址:https://www.cnblogs.com/PheonixHkbxoic/p/5708749.html
Copyright © 2011-2022 走看看