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

如何使用JavaScript的reduce方法对数组元素值进行求和?

How to Sum Array Elements with JavaScript's reduce Method

Hey there! Let's break down how to fix your reduce sum code and understand how the method works properly.

First, let's look at the issue in your original code:

const numberArray = [2, 23, 3, 4, 5, 6, 7, 8, 9, 10]; 
const added = numberArray.reduce((sum, indexValue, index, numberArray) => { 
  if(index === 0) { 
    console.log(`${index} : ${indexValue}`); 
  }else{ 
    return sum += indexValue; 
  } 
}, 0); 
console.log(added);

The problem here is that when index === 0, your callback doesn't return a value. Since you set an initial value of 0, the first iteration starts with sum = 0 and indexValue = 2. But because you don't return anything for the first index, sum becomes undefined in the next iteration—ruining all subsequent calculations.

Fixed Version of Your Code

To fix this, we just need to make sure the callback returns the updated sum every time, even when we log the first element:

const numberArray = [2, 23, 3, 4, 5, 6, 7, 8, 9, 10]; 
const added = numberArray.reduce((sum, indexValue, index) => {
  // Log the first element if needed
  if(index === 0) {
    console.log(`${index} : ${indexValue}`);
  }
  // Always return the accumulated sum
  return sum + indexValue;
}, 0); 
console.log(added); // Output: 77

A More Concise Approach

If you don't need to log the first element, you can simplify this to a one-liner—this is the standard way to sum an array with reduce:

const numberArray = [2, 23, 3, 4, 5, 6, 7, 8, 9, 10];
const added = numberArray.reduce((sum, num) => sum + num, 0);
console.log(added); // Output: 77

Quick Notes on reduce

  • The first argument (sum here) is the accumulator: it holds the result of all previous iterations.
  • The second argument (num) is the current element being processed.
  • The final 0 is the initial value for the accumulator. Adding this is safer because if your array is empty, reduce won't throw an error. If you omit it, reduce will use the first element of the array as the initial value (which works for non-empty arrays, but isn't as robust).

内容的提问来源于stack exchange,提问作者Femi-Laizer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:58:15