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

如何在JavaScript中用reduce函数计算字符串数组的总长度

问题解决:reduce计算字符串数组总长度返回NaN的修复方案

你的代码返回NaN的核心原因是没有给reduce指定初始值,导致累加过程中类型出现异常:

  • 第一次循环时,accumulator是数组第一个元素'apple'(字符串类型),取length得到5,加上currentValue('orange')的长度6,返回数字11
  • 第二次循环时,accumulator变成了数字11,而数字没有length属性,此时accumulator.length会得到undefined,undefined和数字相加直接得到NaN,后续循环都会基于NaN计算,最终输出结果自然是NaN

修复方案(推荐写法)

给reduce传入第二个参数作为初始累加值(数字0),让accumulator从一开始就是数字类型,直接累加每个字符串的长度即可:

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];

const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
  return accumulator + currentValue.length;
}, 0); // 指定初始累加值为0

console.log(sumtwo); // 输出:25(5+6+5+9的总和)

可选兼容写法(不推荐,可读性较差)

如果坚持不设置初始值,需要手动判断accumulator的类型,处理第一次循环时的字符串情况:

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];

const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
  const accValue = typeof accumulator === 'string' ? accumulator.length : accumulator;
  return accValue + currentValue.length;
});

console.log(sumtwo); // 输出:25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:10:45