如何用map()、filter()或reduce()替代求和代码中的for循环?
Refactoring
sumAll to Use reduce() Instead of a For Loop Hey there! Let's swap out that for loop in your sumAll function with array methods—since we're calculating a cumulative sum, reduce() is the ideal choice here. Here's how to do it cleanly:
const sumAll = (arr) => { // Make sure start is the smaller number, end is the larger const [start, end] = arr[0] > arr[1] ? [arr[1], arr[0]] : arr; // Generate the full range of numbers, then reduce to get the sum return Array.from({ length: end - start + 1 }, (_, index) => start + index) .reduce((accumulator, currentNumber) => accumulator + currentNumber, 0); }; console.log(sumAll([1, 4])); // Logs 10 (1+2+3+4) console.log(sumAll([10, 5])); // Logs 40 (5+6+7+8+9+10)
Breakdown of the changes:
- First, we use destructuring to set
startandendcorrectly, regardless of the order in the input array. No messy swapping needed here! Array.from()creates an array of all integers fromstarttoend. Thelengthparameter isend - start + 1to make sure we include both endpoints (e.g., from 1 to 4 is 4 numbers, so 4-1+1=4).reduce()iterates over the array, adding each number to theaccumulator(which starts at 0). This replaces the for loop's manual sum accumulation.
If you're curious, there's also a math shortcut using the arithmetic series formula ((numberOfTerms / 2) * (start + end)) that avoids creating an array entirely, but since you specifically asked to use map(), filter(), or reduce(), the above approach is perfect.
内容的提问来源于stack exchange,提问作者phuocding
相关产品推荐
相关产品推荐

