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

为何JavaScript多数组求和代码中reduce方法的初始值0是必需的?

Why is the initial value 0 required in Array.reduce() for my multi-array element sum function?

Here's the JavaScript code I wrote to sum elements at corresponding positions across multiple arrays:

function addTogether (...arrays) { 
  let result = []; 
  let arrayLength = Math.max(...arrays.map(array => array.length)); 
  for (let i = 0; i < arrayLength; i++) { 
    result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0)); 
  } 
  return result 
} 
test(addTogether([1, 2, 3], [4, 5], [6]), [11, 7, 3]);

I’ve noticed that the 0 (the initial value passed to reduce) after the comma in arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0) is mandatory—if I remove it, the code doesn’t work as expected. But I don’t understand exactly what this 0 does. Can someone break down the principle behind it?


Answer:

Great question! Let’s break down exactly why that 0 is non-negotiable here:

First, let’s recap how Array.reduce() works without an initial value: when you omit the initial value, reduce takes the first element of the array as the starting value for your accumulator (that’s the sum variable in your callback), then starts iterating from the second element.

In your code, arrays is an array of arrays—like [[1,2,3], [4,5], [6]] when you run your test case. If you remove the 0, here’s what happens in the first loop iteration (when i=0):

  • The first sum value is the first element of arrays: the array [1,2,3]
  • Next, the callback runs with sum = [1,2,3] and arr = [4,5]. You try to add sum + (arr[0] || 0)—but JavaScript can’t add an array and a number directly. It converts the array to a string ("1,2,3") and concatenates it with 4, giving you "1,2,34"
  • Then the callback runs again with sum = "1,2,34" and arr = [6]. Now you’re concatenating "1,2,34" with 6, resulting in "1,2,346"
  • This string gets pushed to result instead of the number 11 you expect—total chaos!

When you add the initial value 0, you fix this entirely:

  • sum starts as the number 0, so every operation in the callback is a numeric addition, not string concatenation
  • First iteration: 0 + 1 = 1 (from [1,2,3][0])
  • Second iteration: 1 + 4 = 5 (from [4,5][0])
  • Third iteration: 5 + 6 = 11 (from [6][0])
  • You get the correct numeric sum, which is exactly what you want.

As an extra bonus, providing an initial value also prevents errors if arrays were ever empty (without it, reduce would throw a TypeError when trying to process an empty array).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:17:45