简体   繁体   中英

Javascript Equivalent of Python's operator.add

Does javascript have an equivalent to Python's operator.add , or any other binary operators?

In 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]))

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

The way you have done it is the most concise way that I'm aware of in JavaScript. You might want to supply a default value for your reduce to protect against an empty input array:

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

Javascript is a low level language : no way until you define it.

See Array.prototype.reduce

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM