zoukankan      html  css  js  c++  java
  • javaScript中的return、break和continue

    一、使用的环境

      (1)return只能在函数里面使用

      (2)break、continue 在循环(for、while、do.....while)中使用 ,不能在forEach中使用。

            const arr = [1, 2, 3, 4, 5];
            for(let i of arr){
                if(i == 2){
                    break;  // 跳出整个循环
                }
                console.log(i);     //1
            }
            console.log("............");
            let index = 0;
            console.log("............");
            while(index <= 0 && index >=-5){
                index--;
                if(index == -2){
                    continue;   //终止当前循环,继续下次循环
                }
                console.log(index);//   -1   -3   -4     -5   -6
            }
            console.log("............");
    
            //do....while中的运用
            do{
                index++;
                console.log(index);     // -5  -4  -3   -2
                if(index == -2){
                    break;
                }
            }while(index<20)
    
            console.log("............");
    
            //forEach 中不可使用
            //报错    Uncaught SyntaxError: Illegal break statement    at Array.forEach (<anonymous>)
            arr.forEach((item,index) => {
                if(index == 10){
                    break;  
                }
                console.log(index);
            });

    二、效果差异

      (1)break退出该循环,而continue只是退出当前的这一次循环。

      (2)return是退出循环,return 后面的语句不会再执行了。

            const arr = [1, 2, 3, 4, 5];
            for(let i of arr){
                if(i == 2){
                    break;
                }
                console.log(i);     //1
            }
            console.log(34534);    //34534
            
            
            console.log("--------------");
    
            for(let i of arr){
                if(i == 2){
                    continue;
                }
                console.log(i);     //1  3  4   5  
            }
            console.log("--------------");
    
            demo(arr);
            function demo(arr){
                for(let i of arr){
                    if(i == 2){
                        return;
                    }
                    console.log(i);     //1
                }
                console.log(34534);    // 没有输出
            }
  • 相关阅读:
    Sublime Text 3 安装及常用插件配置
    利用事件对象实现线程同步
    基于UDP(面向无连接)的socket编程
    基于TCP(面向连接)的socket编程
    基于TCP(面向连接)的socket编程
    响应式布局之媒体查询 @media
    (function($){})(jQuery)---Javascript的神级特性:闭包
    noConflict()
    $.extend()与$.fn.extend()
    Web中的宽和高
  • 原文地址:https://www.cnblogs.com/zxn-114477/p/14424487.html
Copyright © 2011-2022 走看看