js笔记之switch-case

switch 语句来选择要执行的多个代码块之一。switch 不能处理大于小于的

语法

switch(n)
{
    case 1:
        执行代码块 1
        break;
    case 2:
        执行代码块 2
        break;
    default:
        与 case 1 和 case 2 不同时执行的代码
}

工作原理:首先设置表达式 n(通常是一个变量)。随后表达式的值会与结构中的每个 case 的值做比较。如果存在匹配,则与该 case 关联的代码块会被执行。请使用 break 来阻止代码自动地向下一个 case 运行。

注意,如果没有break 匹配上一条以后,下边的条件不匹配,但是会执行代码块的



<!DOCTYPE html>
<html lange = "en">
<head>
    <meta charset="UTF-8">
    <title>js之switch  </title>
</head>
<body>
    <h1>js之switch  </h1>
    <script type="text/javascript">
        var i = 4;
        switch (i) {
            case 1: {
                document.write("星期一");
            }
            case 2: {
                document.write("星期二");
            }
            case 3: {
                document.write("星期三");
            }
            case 4: {
                document.write("星期四");
            }
            case 5: {
                document.write("星期五");
            }
            case 6: {
                document.write("星期六");
            }    
            case 7: {
                document.write("星期日");
            }
        } 

    </script>


</body>

结果如下

image

即4前边的代码都没有执行,到第4条匹配以后,后续的不管是否匹配都执行都执行

加上break后

<!DOCTYPE html>
<html lange = "en">
<head>
    <meta charset="UTF-8">
    <title>js之switch  </title>
</head>
<body>
    <h1>js之switch  </h1>
    <script type="text/javascript">
        var i = 4;
        switch (i) {
            case 1: {
                document.write("星期一");break;
            }
            case 2: {
                document.write("星期二");break;
            }
            case 3: {
                document.write("星期三");break;
            }
            case 4: {
                document.write("星期四");break;
            }
            case 5: {
                document.write("星期五");break;
            }
            case 6: {
                document.write("星期六");break;
            }    
            case 7: {
                document.write("星期日");
            }
        } 

    </script>
</body>

运行结果如下

image

switch 的一个用法

当不同的条件产生同一个动作的时候,用法比较简单

switch (i) {
            case 1:
            case 2: 
            case 3: 
            case 4: 
            case 5: {
                document.write("工作");break;
            }
            case 6:     
            case 7: {
                document.write("休息");
            }
        }


image

人在中年,一事无成,瞎学
原文地址:https://www.cnblogs.com/jilingxf/p/13833146.html