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

中断声明

break语句用于提早退出循环,使之脱离封闭的花括号。break语句退出循环。  

让我们来看一个JavaScript中的break语句示例。以下示例说明了带有while循环的break语句的用法。请注意,一旦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语句在循环中进行了一次迭代。此示例说明了带有while循环的continue语句的用法。请注意,当变量x中的索引达到8时,如何使用continue语句跳过打印-

示例

<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>