如何终止 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.
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP