首頁 > web前端 > js教程 > 主體

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

WBOY
發布: 2023-08-23 19:53:02
轉載
977 人瀏覽過

如何停止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; 
   }
});
登入後複製

在上述語法中,如果條件變成真,則不會執行元素的回呼函數的程式碼。

Example 1

的中文翻譯為:

範例1

#In the example below, We are using the forEach() method with the array of strings. We call the callback function for every element, which prints every element. We used the condition that if index > 2, it returns from the callback function. So it will not print the element.

<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()方法,但如果條件為真,它將作為一個連續關鍵字運作。

透過拋出異常停止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) {
}
登入後複製

In the above syntax, we have used the throw keyword to throw the exception and break the forEach() method.

Example 2

的中文翻譯為:

範例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>
登入後複製

In the above output, users can observe that it stops printing the elements after it finds the number type element in the array.

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

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

文法

Users can follow the syntax below to use the for-loop with the break keyword.

for ( ){
   if (condition) {
      break;
   }
}
登入後複製

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

Example 3

的中文翻譯為:

範例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()方法來提高效能。

以上是如何停止JavaScript中的forEach()方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!