🚧 施工中
JS⟩ syntax ⟩ for loops ⟩ arr.forEach()
to skip a case, use return.
⭐️ there's no way to break/continue in this method❗️
💾 程式:replit
let array = [1, 2, 3, 4, 5]; // ⭐️ skip a case with `return` array.forEach(n => { if (n % 2 !== 0) return; // ✅ use `return` console.log(n); // 2, 4 }); // ⭐️ skip cases with `filter()` array .filter(n => n % 2 == 0) // ✅ use `filter` .forEach(n => console.log(n)); // 2, 4aa
replit:no break/continue in forEach()
let array = [1, 2, 3, 4, 5]; // ❌ can't use `break` in .forEach() array.forEach(n => { if (n % 2 !== 0) break; // ^^^^^ // ⛔ SyntaxError: // "Illegal break statement" }); // ❌ can't use `continue` in .forEach() array.forEach(n => { if (n % 2 !== 0) continue; // ^^^^^^^^ // ⛔ SyntaxError: // "Illegal continue statement: no surrounding iteration statement" });
Using Continue in JavaScript forEach() - use return to skip a case
Array.prototype.forEach()
to do:
break statement
continue statement
Last updated 2 months ago
Was this helpful?