4

我正在尝试这样做,但是使用 CoffeeScript:

# ruby:
items.map {|item| item.price * item.quantity }.reduce(:+)

到目前为止我所拥有的:

# coffeescript:
item.price * item.quantity for item in items

如何对数组中的所有项目求和?更一般地说,我怎样才能对数组中的所有项目执行任何操作(在 Ruby 中,这将是injector reduce)?

4

3 回答 3

3

没关系,我找到了。它完成了reduce

(item.price * item.quantity for item in items).reduce (x, y) -> x + y
于 2012-06-19T02:51:25.290 回答
2

我不知道一般的减少功能,但对于累加器,你可以做

sum = 0
sum += item.price * item.quantity for item in items
于 2012-06-19T02:52:06.227 回答
0

更通用的 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
于 2013-05-31T07:09:53.493 回答