如何终止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.
}热门推荐
7 简短元宵节祝福语
10 生日祝福语 简短独特潮
11 公司最好的祝福语简短
12 生日祝福语宿舍舍友 简短
13 学校元旦祝福语和简短
14 伴娘祝福语简短朋友的话
15 高考成绩出祝福语 简短
16 女儿蛋糕祝福语简短精辟
17 兄弟生日恶搞祝福语简短
18 成年礼简短的祝福语