ไม่สามารถ break จาก forEach method ได้ และไม่มีทาง escape loop (นอกจากการ throw exception)
ใช้ฟังก์ชันอื่นเช่น _.find จาก lodash แทน
_.find - break ออกจาก loop เมื่อเจอ element ตัวอย่าง:
ตัวอย่าง
_.find([1, 2, 3, 4], (element) => { // Check your condition here if (element === 2) { return true; } // Do what you want with the elements here // ... });Throw exception จาก 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. }