javascript是否具有与Python的operator.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(???)
Javascript是一种低级语言:在你定义它之前是不可能的。你知道吗
见Array.prototype.reduce
您所使用的方式是我所知道的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))
;相关问题 更多 >
编程相关推荐