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

如何用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 start and end correctly, regardless of the order in the input array. No messy swapping needed here!
  • Array.from() creates an array of all integers from start to end. The length parameter is end - start + 1 to 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 the accumulator (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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:36:23