如何终止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.
}热门推荐
10 女儿结婚账单祝福语简短
11 送女士祝福语长辈简短
12 治愈语句祝福语大全简短
13 最真的新春祝福语简短
14 周一情人祝福语简短
15 诗词送行祝福语大全简短
16 生女儿的祝福语简短
17 中秋送健康祝福语简短
18 期末寄语简短祝福语高中