首页 > 解决方案 > Javascript 等效于 Python 的 operator.add

问题描述

javascript 是否具有等效于 Pythonoperator.add或任何其他二元运算符的功能?

在 Python 中:

from operator import add
from functools import reduce

# prints 15, requires defining the addition operator
print(reduce(lambda a, b: a + b, [1, 2, 3, 4, 5]))

# prints 15, does not require defining the addition operator
print(reduce(add, [1, 2, 3, 4, 5]))

在 Javascript 中:

// prints 15, requires defining the addition operator
console.log([1, 2, 3, 4, 5].reduce((a,b) => a + b))

// is there a way to do this without defining the addition operator?
console.log([1, 2, 3, 4, 5].reduce(???)

标签: javascriptpython

解决方案


你这样做的方式是我在 JavaScript 中所知道的最简洁的方式。您可能希望为您提供一个默认值reduce以防止出现空输入数组:

console.log([1,2,3,4,5].reduce((a,b) => a + b, 0))

// throws a TypeError...
console.log([].reduce((a,b) => a + b))


推荐阅读