相当于Python的Javascript运算符.add

2024-04-26 11:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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(???)

Tags: thefromimportlogaddreduce运算符javascript
2条回答

Javascript是一种低级语言:在你定义它之前是不可能的。你知道吗

Array.prototype.reduce

const add = (acc, item) => {
    return acc = acc + item;
});

console.log([1, 2, 3, 4, 5].reduce(add, 0));

您所使用的方式是我所知道的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))

相关问题 更多 >