30秒学会 JavaScript 片段 · 2022年5月26日

30秒学会 JavaScript 片段 – Array sum

Calculates the sum of two or more numbers/arrays.

  • Use Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0.

代码实现

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);

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

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