如何在 JavaScript 中停止 forEach() 方法?


JavaScript 中,程式設計師可以使用 forEach() 方法 迭代陣列元素。我們可以呼叫一個 回撥函式,將其作為 forEach() 方法的引數,用於處理每個陣列元素。

有時,我們可能需要在為某些元素執行回撥函式後停止 forEach() 迴圈。我們可以使用 'break' 關鍵字與普通迴圈一起停止它,如下所示。

for(let i = 0; i < length; i++){
   // code
   if( some condition ){
      break;
   }
}

但是我們不能在 forEach() 方法中使用 'break' 關鍵字。

array.forEach(element => {
   // code
   if( some condition ){
      break;
   }
});

上述程式碼不會停止 forEach() 迴圈的執行。

本教程將講解停止 JavaScript 中 forEach() 迴圈的各種方法。

使用 return 關鍵字

return 關鍵字會停止程式碼的執行。在 forEach() 迴圈中,它起著 continue 語句的作用。

語法

使用者可以按照以下語法使用 return 關鍵字停止 forEach() 方法的執行。

array.forEach(function (element, index) {
   if (condition) {
      return; 
   }
});

在上述語法中,如果條件為真,則不會為該元素執行回撥函式的程式碼。

示例 1

在下面的示例中,我們使用 forEach() 方法處理字串陣列。我們為每個元素呼叫回撥函式,該函式列印每個元素。我們使用了這樣一個條件:如果索引 > 2,則從回撥函式返回。因此,它不會列印該元素。

<html>
<body>
   <h2>Using the <i>return keyword</i> to stop the execution of the forEach() loop.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array = ["string1", "string2", 10, 20, false, true];
      function callback(element, index) {
         // stop execution of for-loop
         if (index > 2) {
            return; // works like a continue statement
         }
         output.innerHTML += "The array element is " + element + "<br/>";
      }
      array.forEach(callback);
   </script>
</body>
</html>

‘return’ 關鍵字不會中斷 forEach() 方法,但如果條件為真,它會起 continue 關鍵字的作用。

透過丟擲異常來停止 forEach() 迴圈

停止 forEach() 迴圈的另一種方法是使用 try-catch 語句。當我們想要停止 forEach() 方法的執行時,可以丟擲錯誤。此外,我們可以在 'catch' 塊中捕獲錯誤。我們可以在 'finally' 塊中執行 forEach() 方法之後需要執行的任何程式碼。

語法

使用者可以按照以下語法使用 try-catch 語句停止 forEach() 方法。

try {
   array.forEach((ele) => {
      if (condition) {
         throw new Error("Break the loop.")
      }
   })
} catch (error) {
}

在上述語法中,我們使用了 throw 關鍵字來丟擲異常並中斷 forEach() 方法。

示例 2

在下面的示例中,我們使用了帶有 try-catch 語句的 forEach() 方法。在 forEach() 方法的回撥函式中,我們檢查元素型別,如果我們發現任何型別為“number”的元素,我們就會丟擲錯誤。

因此,它將停止 forEach() 方法的執行。

<html>
<body>
   <h2>Using the <i>try-catch statement</i> to stop the execution of the forEach() loop.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let array = ["Cpp", "c", "Java", "JavaScript", 06, true, 43, false];
      try {
         array.forEach((ele) => {
            if (typeof ele == "number") {
               throw new Error("Break the loop.")
            }
            output.innerHTML += "Element value is " + ele + "<br/>";
         })
      } catch (error) {
         output.innerHTML += "Exception thrown from the forEach loop. " + error;
      }
   </script>
</body>
</html>

在上面的輸出中,使用者可以觀察到,在陣列中找到 number 型別元素後,它停止了列印元素。

使用帶 break 關鍵字的普通 for 迴圈

停止 forEach() 方法執行的最佳解決方案是用普通的 for 迴圈替換 forEach() 迴圈,並使用 break 關鍵字來停止其執行。

語法

使用者可以按照以下語法使用帶 break 關鍵字的 for 迴圈。

for ( ){
   if (condition) {
      break;
   }
}

在上述語法中,當特定條件為真時,我們使用 break 關鍵字停止 for 迴圈的執行。

示例 3

在下面的示例中,我們定義了各種值的陣列。我們使用普通的 for 迴圈迭代陣列,如果陣列值大於 30,我們使用 break 關鍵字停止 for 迴圈的執行。

<html>
<body>
   <h2>Using the normal for-loop with break keyword to stop the execution of for-loop. </h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let arrayElements = [10, 20, 30, 40, 50, 60, 70, 80, 90];
      output.innerHTML += "Some array elements are "
      for (let k = 0; k < arrayElements.length; k++) {
         if (arrayElements[k] > 30) {
            break;
         }
         output.innerHTML += arrayElements[k] + " , ";
      }
   </script>
</body>
</html>

方法。第一種方法不會中斷迴圈,而是會作為 'continue' 語句工作。第二種方法使用 try-catch 語句來中斷 forEach() 方法。我們不能僅僅為了中斷 forEach() 迴圈而在實際開發中丟擲錯誤。因此,不建議使用第一種和第二種方法。

在第三種方法中,我們用普通的 for 迴圈替換了 forEach() 方法,並使用了 break 關鍵字。第三種方法可以正常工作,但是普通的 for 迴圈 迭代元素的速度可能比 forEach() 方法慢。因此,使用者也可以嘗試使用 array.some()array.each() 方法 來提高效能。

更新於:2023年9月12日

46K+ 瀏覽量

啟動你的 職業生涯

完成課程後獲得認證

開始
廣告