![](/img/trans.png)
[英]Unclear about returning from javascript forEach loop inside a function
[英]Javascript returning in forEach loop
我經常遇到這種情況,只是想知道我的解決方案是否是最好的,以及是否有更好的解決方案。 很多情況下,我有一個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
或其他方法?
你不能break
的forEach
。 它將在數組的每個元素上運行。 您可以使用some
方法檢查至少一項是否為isInvalid
。 一旦找到具有isInvalid = true
的項目,這將短路
if (emailList.some(element => element.isInvalid))
return
您的forEach為每個元素執行箭頭功能 ,而不檢查其結果。 我不建議使用try-catch
因為它非常慢。 嘗試將for-of
與return
一起使用(或break
不返回,而僅中斷for循環並繼續執行for
以下代碼)
function start() { const emailList = ['abc@test.com', 'invalid 1', 'invalid 2']; const emailErrors = []; for(let element of emailList) { console.log(element); if(!/@/.test(element)) return; // some validation (missing @ char) }; } start();
您可以使用Array.prototype.every()。
every()方法測試數組中的所有元素是否通過提供的函數實現的測試。 它返回一個布爾值。
function validateEmailList(element) {
return element.isInvalid;
}
console.log(emailList.every(validateEmailList));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.