為什麼 JavaScript 中的“continue”語句不好?


“continue”語句的使用使得程式碼變得難以理解。在大多數情況下,continue 的使用意味著你的迴圈中的條件不足。為了避免這種情況,可以將其新增到條件本身中或在迴圈中使用 if。

但是,“continue”如果使用不一致或不當,就不好,否則它是一個有用的語句,可以節省大量的記憶體和程式碼行。

示例

我們來看一個 continue 語句的示例

線上演示

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

更新時間: 2020 年 1 月 8 日

572 次檢視

開啟你的 事業

完成課程可獲得認證

開始
廣告