JavaScript - continue 語句



JavaScript 中的 continue 語句用於跳過迴圈的當前迭代並繼續執行下一迭代。它通常與 if 語句結合使用,以檢查條件並在滿足條件時跳過迭代。

JavaScript continue 語句告訴直譯器立即開始迴圈的下一輪迭代並跳過剩餘的程式碼塊。當遇到 continue 語句時,程式流程會立即移動到迴圈檢查表示式,如果條件仍然為真,則開始下一輪迭代,否則控制權將退出迴圈。

語法

JavaScript 中 continue 語句的語法如下:

continue;
OR
continue label;

我們可以在迴圈中使用 continue 語句,例如 for 迴圈、while 迴圈、do…while 迴圈等。

我們將在接下來的章節中學習如何將 'continue' 語句與 'label' 語句一起使用。

帶 for 迴圈的 continue 語句

下面的示例將 continue 語句與 for 迴圈一起使用。在迴圈中,當 x 的值為 3 時,它將執行 continue 語句以跳過當前迭代並移動到下一迭代。

在輸出中,您可以看到迴圈不會列印 3。

示例

<html>
<head>
   <title> JavaScript - Continue statement </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      output.innerHTML += "Entering the loop. <br /> ";
      for (let x = 1; x < 5; x++) {
         if (x == 3) {
            continue;   // skip rest of the loop body
         }
         output.innerHTML += x + "<br />";
      }
      output.innerHTML += "Exiting the loop!<br /> ";
   </script>
</body>
</html>

輸出

Entering the loop.
1
2
4
Exiting the loop!

帶 while 迴圈的 continue 語句

我們在下面的示例中將 while 迴圈與 continue 語句一起使用。在 while 迴圈的每次迭代中,我們將 x 的值加 1。如果 x 的值等於 2 或 3,則跳過當前迭代並移動到下一迭代。

在輸出中,您可以看到程式碼不會列印 2 或 3。

示例

<html>
<head>
   <title> JavaScript - Continue statement </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      var x = 1;
      output.innerHTML += "Entering the loop. <br /> ";
      while (x < 5) {
         x = x + 1;
         if (x == 2 || x == 3) {
            continue;   // skip rest of the loop body
         }
         output.innerHTML += x + "<br />";
      }
      output.innerHTML += "Exiting the loop!<br /> ";
   </script>
</body>
</html>

輸出

Entering the loop.
4
5
Exiting the loop!

帶巢狀迴圈的 continue 語句

您可以將 continue 語句與巢狀迴圈一起使用,並跳過父迴圈或子迴圈的迭代。

示例

下面的程式碼中,父迴圈遍歷 1 到 5 的元素。在父迴圈中,我們使用 continue 語句在 x 的值為 2 或 3 時跳過迭代。此外,我們還定義了巢狀迴圈。在巢狀迴圈中,當 y 的值為 3 時,我們跳過迴圈迭代。

在輸出中,您可以觀察 x 和 y 的值。您不會看到 x 的 2 或 3 值以及 y 的 3 值。

<html>
<head>
   <title> JavaScript - Continue statement </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      output.innerHTML += "Entering the loop. <br /> ";
      for (let x = 1; x < 5; x++) {
         if (x == 2 || x == 3) {
            continue;   // skip rest of the loop body
         }
         for (let y = 1; y < 5; y++) {
            if (y == 3) {
               continue;
            }
            output.innerHTML += x + " - " + y + "<br />";
         }
      }
      output.innerHTML += "Exiting the loop!<br /> ";
   </script>
</body>
</html>

輸出

Entering the loop.
1 - 1
1 - 2
1 - 4
4 - 1
4 - 2
4 - 4
Exiting the loop!
廣告