In Lisp , this'd be exactly the job for reduce
.
(在Lisp中 ,这正是reduce
工作量的工作。)
You'd see this kind of code: (您会看到以下代码:)
(reduce #'+ '(1 2 3)) ; 6
Fortunately, in JavaScript, we also have reduce
!
(幸运的是,在JavaScript中,我们也有reduce
!)
Unfortunately, +
is an operator, not a function. (不幸的是, +
是运算符,而不是函数。)
But we can make it pretty! (但是我们可以使其漂亮!)
Here, look: (在这里,看看:)
const sum = [1, 2, 3].reduce(add,0); // with initial value to avoid when the array is empty
function add(accumulator, a) {
return accumulator + a;
}
console.log(sum); // 6
Isn't that pretty?
(那不是很漂亮吗?)
:-) (:-))
Even better!
(更好!)
If you're using ECMAScript 2015 (aka ECMAScript 6 ), it can be this pretty: (如果您使用的是ECMAScript 2015(又名ECMAScript 6 ),它可能会很漂亮:)
const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
console.log(sum); // 6
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…