You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript reduce函数第二次迭代后返回undefined问题排查

问题根因

Array.reduce 执行时,每一轮迭代的回调函数必须返回累加器值,这个返回值会作为下一轮迭代的第一个参数传入。
你的代码中回调函数只执行了 total.push(...tempArr) 操作,没有写返回语句,函数默认返回 undefined:

  • 第一轮迭代用初始空数组执行完push后,返回undefined
  • 第二轮迭代时total参数就是undefined,尝试调用undefined.push()会直接触发类型错误,导致后续逻辑无法正常执行。
修复代码

只需要在回调函数末尾返回累加后的total数组即可:

const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

const colors = data.reduce((total,item)=>{
  let tempArr = item.c
  total.push(...tempArr)
  // 返回累加结果,作为下一轮迭代的累加器初始值
  return total
},[]) 

console.log(colors)
// 运行输出:['blue', 'green', 'green', 'black', 'orange', 'blue', 'green', 'red']

如果想要更简洁的写法,也可以直接用concat合并数组后返回,不需要手动执行push操作:

const colors = data.reduce((total, item) => total.concat(item.c), [])

内容的提问来源于stack exchange,提问作者amir_70

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 10:18:08