下面代码的输出是什么?
const numbers = [1, 2, 3, 4, 5, 6];
numbers.forEach((num, index) => {
if (num === 3) {
console.log(`遇到数字 3,使用 return 跳过`);
return;
}
if (num === 5) {
console.log(`遇到数字 5,使用 return 跳过`);
return;
}
console.log(`处理数字: ${num}, 索引: ${index}`);
});
参考答案
输出:
处理数字: 1, 索引: 0
处理数字: 2, 索引: 1
遇到数字 3,使用 return 跳过
处理数字: 4, 索引: 3
遇到数字 5,使用 return 跳过
处理数字: 6, 索引: 5
核心考点
forEach 的回调里的 return **只能终止当前这一次回调,等价于普通 for 的 continue,不能终止整个 forEach 循环**,下一个元素依旧继续执行Tutorials ...。
num=3:打印提示 → return,跳过后面那句处理数字,继续走到 4num=5:打印提示 → return,跳过后面那句,继续走到 6
面试追加问题
- 想彻底跳出整个遍历,
forEach原生不支持break,怎么办?
- 改用普通 for /for…of
- 使用
some/every,返回 true/false 提前终止
- 如果我写
break在 forEach 回调里面会怎样?
→ 直接语法报错:Illegal break statement