如何終止 javascript forEach()?
你無法跳出 forEach 方法,它也沒有提供退出迴圈的方法(除了丟擲異常)。
你可以改用其他功能,如 lodash 中的 _.find −
_.find − 當找到元素時,會退出迴圈。例如,
示例
_.find([1, 2, 3, 4], (element) => {
// Check your condition here
if (element === 2) {
return true;
}
// Do what you want with the elements here
// ...
});從 forEach 中丟擲異常。例如,
示例
try {
[1, 2, 3, 4].forEach((element) => {
// Check your condition here
if (element === 2) {
throw new Error();
}
// Do what you want with the elements here
// ...
})
} catch (e) {
// Do nothing.
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP