我正在尝试这样做,但是使用 CoffeeScript:
# ruby:
items.map {|item| item.price * item.quantity }.reduce(:+)
到目前为止我所拥有的:
# coffeescript:
item.price * item.quantity for item in items
如何对数组中的所有项目求和?更一般地说,我怎样才能对数组中的所有项目执行任何操作(在 Ruby 中,这将是injector reduce)?
我正在尝试这样做,但是使用 CoffeeScript:
# ruby:
items.map {|item| item.price * item.quantity }.reduce(:+)
到目前为止我所拥有的:
# coffeescript:
item.price * item.quantity for item in items
如何对数组中的所有项目求和?更一般地说,我怎样才能对数组中的所有项目执行任何操作(在 Ruby 中,这将是injector reduce)?
没关系,我找到了。它完成了reduce
(item.price * item.quantity for item in items).reduce (x, y) -> x + y
我不知道一般的减少功能,但对于累加器,你可以做
sum = 0
sum += item.price * item.quantity for item in items
更通用的 reduce 函数可能如下所示:
total = ((agg = 0) ->
agg + item.price * item.quantity
)(total, item) for item in items
或者
result = ((aggregate = 'default value') ->
// function body changing, then returning aggregate
aggregate
)(result, i) for i in some_array