如何在 JavaScript 中使用 break 語句退出迴圈?


break 語句用於提前退出迴圈,跳出包圍它的花括弧。

示例

你可以嘗試執行以下程式碼來學習如何使用 break 語句退出迴圈

即時演示

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

更新於: 08-01-2020

142 次閱讀

開啟你的 職業生涯

完成課程獲得證書

開始吧
廣告
© . All rights reserved.