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]))
在Java语言中:
// 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(???)
答案 0 :(得分:1)
您执行此操作的方式是我在JavaScript中意识到的最简洁的方式。您可能需要为[
'label'=> 'Child',
'value' => function($data){
return $data->order->kids;
}
],
提供默认值,以防止输入数组为空:
reduce
答案 1 :(得分:0)
Javascript是一种低级语言:除非您定义它,否则是不可能的。
const add = (acc, item) => {
return acc = acc + item;
});
console.log([1, 2, 3, 4, 5].reduce(add, 0));