JavaScript 中 break 和 continue 语句的区别是什么?


break 语句

break 语句用于提前退出循环,跳出包围它的花括号。break 语句退出循环。

让我们看一个 JavaScript 中 break 语句的例子。以下示例说明了 break 语句与 while 循环一起使用的情况。请注意,一旦 x 达到 5 并到达紧接在闭合花括号下方的 document.write (..) 语句时,循环是如何提前退出的,

示例

<html>
   <body>
      <script>
         var x = 1;
         document.write("Entering the loop<br /> ");
         while (x < 20) {
            if (x == 5) {
               break;     // breaks out of loop completely
            }
            x = x +1;
            document.write( x + "<br />");
         }

         document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>

continue 语句

continue 语句告诉解释器立即开始循环的下一轮迭代,并跳过剩余的代码块。当遇到 continue 语句时,程序流程立即移动到循环检查表达式,如果条件仍然为真,则开始下一轮迭代,否则控制权将退出循环。

continue 语句在循环中跳过一次迭代。此示例说明了 continue 语句与 while 循环一起使用的情况。请注意,如何使用 continue 语句在变量 x 中保存的索引达到 8 时跳过打印 -

示例

<html>
   <body>
      <script>
         var x = 1;
         document.write("Entering the loop<br /> ");

         while (x < 10)  {
            x = x+ 1;
            if (x == 8){
               continue;  // skip rest of the loop body
            }
            document.write( x + "<br />");
         }
         document.write("Exiting the loop!<br /> ");
      </script>
   </body>
</html>

更新于: 2020年6月13日

458 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.