如何使用JavaScript的reduce方法对数组元素值进行求和?
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 (
sumhere) is the accumulator: it holds the result of all previous iterations. - The second argument (
num) is the current element being processed. - The final
0is the initial value for the accumulator. Adding this is safer because if your array is empty,reducewon't throw an error. If you omit it,reducewill 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

