如何使用JavaScript的reduce对含undefined值的数组求和?
解决reduce对含undefined数组求和返回NaN的问题
嘿,这个问题我之前也踩过坑!当数组里混着undefined时,直接用reduce求和会返回NaN,核心原因是**undefined和数字相加会得到NaN**,之后的所有累加操作都会继承这个NaN。不过咱们有好几种简单的办法解决:
方法1:在reduce回调中把undefined转为0
可以用空值合并运算符(??)或者逻辑或(||),把undefined替换成0再参与计算:
const numArray = [2, undefined, 7, undefined, 4]; const total = numArray.reduce((accumulator, current) => accumulator + (current ?? 0), 0); console.log(total); // 输出13
- 用
current ?? 0更精准:只会把undefined或null转为0,不会影响数组里的合法数字(包括0); - 如果确定数组里没有0,用
current || 0也能达到效果,但??的语义会更清晰。
方法2:先过滤掉undefined再求和
先通过filter把数组里的undefined去掉,剩下纯数字数组再用reduce求和:
const numArray = [2, undefined, 7, undefined, 4]; const total = numArray.filter(item => typeof item === 'number') .reduce((accumulator, current) => accumulator + current, 0); console.log(total); // 输出13
这个方法的好处是能彻底清理掉非数字项,适合数组里可能混有其他非数字类型(比如字符串)的场景。
方法3:在reduce回调中做严谨的类型判断
如果需要更严谨的逻辑(比如排除NaN等无效数字),可以在回调里加类型校验:
const numArray = [2, undefined, 7, NaN, 4]; const total = numArray.reduce((accumulator, current) => { // 只累加合法的数字 if (typeof current === 'number' && !isNaN(current)) { return accumulator + current; } return accumulator; }, 0); console.log(total); // 输出13
这个方案能应对更复杂的数组内容,避免意外的NaN出现。
另外要注意:一定要给reduce设置初始值(这里的0),如果不设置初始值,当数组第一个元素是undefined时,accumulator会直接是undefined,第一步就会得到NaN。
内容的提问来源于stack exchange,提问作者user4602228
相关产品推荐
相关产品推荐

