【发布时间】:2019-05-22 05:35:48
【问题描述】:
我经常遇到这种情况,只是想知道我的解决方案是否是最好的,以及是否有更好的解决方案。很多情况下我有一个forEach 循环,我想检查是否有任何值不正确,如果是,则结束代码(return)。这是我在没有循环的情况下会做的事情:
const email = '...';
if (email.isInvalid) return;
在循环中我会这样做:
const emailList ['...', '...', '...'];
const emailErrors = [];
emailList.forEach((element) => {
// if (element.isInvalid) return; // This won't work here, it just ends this loop instance, which is my problem
if (element.isInvalid) emailErrors.push(element);
});
if (emailErrors.length > 0) return; // This will end the code correctly
有没有更好的方法来实现这个想法?使用try, catch 或其他?
【问题讨论】:
标签: javascript foreach try-catch