forEach 不返回新数组,返回值恒为 undefined;map 按输入长度返回新数组,必须显式 return;reduce 省略初始值时空数组会报错,应始终传入;链式调用需防御空值。
forEach 遍历数组时,别指望它返回新数组很多人误以为 forEach 能像 map 一样生成新数组,其实它只执行副作用(比如打印、修改外部变量),返回值永远是 undefined。
常见错误现象:
const arr = [1, 2, 3]; const doubled = arr.forEach(x => x * 2); // doubled 是 undefined
for...of 或 map
var 声明的变量会共享同一引用map 返回新数组,但不会改变原数组map 的核心契约是“输入长度决定输出长度”,每个元素必须对应一个返回值。漏掉 return 就会得到 undefined 占位。
典型问题:
const nums = [1, 2, 3];
const squares = nums.map(x => { x * x }); // ❌ 返回 [undefined, undefined, undefined]
nums.map(x => x * x) 或带大括号时显式写 return
(item, index, array),第二个参数是索引,不是当前项map 不合适,选 filter 或 some
reduce 归并时,初始值不传会出事省略 reduce 的第二个参数(初始值)时,它会把第一个元素当初始值,从第二个开始迭代——数组为空就直接报错 Reduce of empty array with no initial value。
容易踩的坑:
const list = []; list.reduce((acc, x) => acc + x); // ❌ TypeError
{},求和用 0
acc 是上一轮返回值,不是原始初始值,别在回调里反复修改它(尤其对象/数组)reduce,先 filter 再 reduce 更清晰组合 filter → map → reduce 很常见,但中间某步返回空数组或 null,后续方法就会崩。
例如:
getData().filter(x => x.active).map(x => x.name).reduce((a, b) => a + b, '')
getData() 返回 null 或 undefined,filter 就会报错?? [] 提供默认空数组,或用可选链 ?.filter
console.log 查中间态实际项目里最常出问题的,不是语法写错,而是没想清楚每一步的输入输出类型,尤其是 reduce 的初始值和 map 的 return 缺失。