您不能脱离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.
}