30秒学会 JavaScript 片段 · 2022年6月20日

30秒学会 JavaScript 片段 – Partial sum array

Creates an array of partial sums.

  • Use Array.prototype.reduce(), initialized with an empty array accumulator to iterate over nums.
  • Use Array.prototype.slice() to get the previous partial sum or 0 and add the current element to it.
  • Use the spread operator (...) to add the new partial sum to the accumulator array containing the previous sums.

代码实现

const accumulate = (...nums) =>
  nums.reduce((acc, n) => [...acc, n + (acc.slice(-1)[0] || 0)], []);

accumulate(1, 2, 3, 4); // [1, 3, 6, 10]
accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]

翻译自:https://www.30secondsofcode.org/js/s/partial-sum-array