คุณไม่สามารถแยกจากเมธอด forEach ได้ และไม่ได้จัดเตรียมให้เพื่อหนีออกจากลูป (นอกเหนือจากการส่งข้อยกเว้น)
คุณสามารถใช้ฟังก์ชันอื่นๆ เช่น _.find จาก lodash แทน −
_.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.
}