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

如何在JavaScript中对数组求和?我的代码为何输出异常?

问题分析与解决

你犯的低级错误很明确:把原数组newresult多套了一层数组,写成了[newresult],这直接导致后续的reduce逻辑完全偏离了预期。

为什么会输出字符串拼接结果?

[newresult]是一个二维数组,里面只有一个元素——就是你的原数组newresult。当你对这个二维数组调用reduce时,回调函数里的currentValue拿到的是整个原数组,而不是数组里的单个数字。

JavaScript里数字和数组做加法时,数组会被自动转换为逗号分隔的字符串(比如0 + [1,2]会得到"01,2"),所以你的代码本质上是把初始值0和原数组的字符串形式拼在了一起,自然就出现了那个奇怪的长字符串。

正确的求和写法

直接对原数组newresult调用reduce就行,不需要额外包裹:

const newresult = [
  1, 0, 3, 0, 0, 0, 1, 2,
  0, 0, 0, 1, 3, 0, 0, 0,
  0, 0, 0, 2, 0, 0, 0, 3,
  0, 0, 2
];

// 简洁写法
const sum = newresult.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 输出:18

// 拆分写法(和你原来的结构对应)
const initialValue = 0;
const sumWithInitial = newresult.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);
console.log(sumWithInitial); // 输出:18

额外补充

如果你的环境支持ES2023及以上,还可以用更简洁的Array.prototype.sum()方法:

const sum = newresult.sum();
console.log(sum); // 输出:18

不过这个方法的兼容性还需要注意,目前大部分现代浏览器已经支持,但如果要兼容旧环境,还是reduce更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:33:24