switch 分支语句的穿透现象 和 break、continue

173 阅读1分钟

穿透现象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        /**
         *  switch 再书写的时候 如果不写 break 会出现穿透现象
         * 
         *      穿透现象:
         *          找到第一个满足的 case 的时候, 开始执行这个代码
         *          执行完毕如果没有 break 会继续执行下一个 case
         *          直到 遇到一个 break 或者 分支语句全部执行完毕
        */

        var a = 1
        switch (a) {
            case 1:
                console.log('case 1 执行')
            case 10:
                console.log('case 10 执行')
            case 20:
                console.log('case 20 执行')
                break
            case 30:
                console.log('case 30 执行')
            case 40:
                console.log('case 40 执行')
            case 100:
                console.log('case 100 执行')
            default:
                console.log('上述情况都不满足的时候, 我会执行')
        }
    </script>
</body>

</html>

优化写法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 穿透语法
        // 根据月份, 输出对应的天数    (2月按照28天)
        
        var month = 2  // 再控制台输出5月有?天
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                console.log('有31天')
                break

            case 4:
            case 6:
            case 9:
            case 11:
                console.log('有30天')
                break

            case 2:
                console.log('有28天')
                break
        }
    </script>
</body>

</html>

continue

  循环控制关键字 continue
  continue  结束本次循环代码的执行,直接跳到下一次的循环

break

 循环控制关键字 break
 break 可以在循环中使用,表示结束循环