foreach / for 循环中断等

98 阅读1分钟

foreach

中断循环

[1, 2, 3].forEach((el) => {
  if (el === 2) throw new Error("2 is not allowed");
  console.log(el); // 1 2 3
});

跳过本次循环

[1, 2, 3].forEach((el) => {
  if (el === 2) return;
  console.log(el); // 1 2 3
});

for循环

中断循环

for (let el of [1, 2, 3]) {
  if (el === 2) break/return;
  console.log(el);
}

跳过本次循环

for (let el of [1, 2, 3]) {
  if (el === 2) continue;
  console.log(el);
}