为何JavaScript多数组求和代码中reduce方法的初始值0是必需的?
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
sumvalue is the first element ofarrays: the array[1,2,3] - Next, the callback runs with
sum = [1,2,3]andarr = [4,5]. You try to addsum + (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 with4, giving you"1,2,34" - Then the callback runs again with
sum = "1,2,34"andarr = [6]. Now you’re concatenating"1,2,34"with6, resulting in"1,2,346" - This string gets pushed to
resultinstead of the number11you expect—total chaos!
When you add the initial value 0, you fix this entirely:
sumstarts as the number0, 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

