TypeError: Reduce 的空 数组使用否 初始值
错误信息
Reduce 的空 数组使用否 初始值
快速摘要
你 called 数组.reduce() on 空数组不使用其次实参 (初始值) — reduce 有无 到开始使用.
为什么发生
Called reduce() on 空数组不使用初始值
数组是 unexpectedly 空 due 到筛选 or 数据 issue
Forgot 到通过初始值 as 其次实参到 reduce
最小示例
✗ 错误代码
const nums = [];
const total = nums.reduce((a, b) => a + b);✓ 修复代码
const nums = [];
const total = nums.reduce((a, b) => a + b, 0);空数组使用否 初始值 有无 到 reduce. 通过 0 as 初始值 到获取 0 for 空数组.
如何诊断
检查如果数组是 空之前 calling reduce
Log 数组长度到 确认它 是空
验证其次实参 (初始值) 是 provided
如何修复
总是 provide 初始值 as 其次实参到 reduce
检查如果数组是 空 and provide 默认 result
Use arr.长度 > 0 ? arr.reduce(fn) : defaultValue
如何预防
总是通过初始值 到 reduce: arr.reduce(fn, initialValue)
验证数组内容之前 reducing