javascript - 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(???)
解决方案
你这样做的方式是我在 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))
推荐阅读
- r - Shiny App中反应式条形图的问题
- compiler-errors - 编译错误:collect2.exe:错误:ld 返回 1 退出状态
- java - 有没有办法让微调器延迟显示其内容,直到发生某种情况?
- python - 在初始化之前获取类 __init__ 参数
- python-3.x - 无法在 VSCode 中使用 numpy 加载 txt 文件
- ajax - 使用codeigniter 3和ajax的带有时间范围的日期范围
- python - 使用 Pandas 过滤 DatetimeIndex
- c++ - 'cin' 没有命名类型
- python - python pandas - 将主df列中的唯一ID添加回存储在数据帧列表中的已处理dfs
- python - 是否可以针对某些注册错误自定义 django.auth 错误消息?