我们可以在 javascript 中做 orders.stream().mapToInt(Order::getQuantity).sum()) 吗?

Ole*_*Ole 2 javascript ecmascript-6

在 Java 中,我使用流来计算这样的订单列表的总和:

orders.stream().mapToInt(Order::getQuantity).sum()
Run Code Online (Sandbox Code Playgroud)

我想知道在遍历 Order 实例数组时,在 javascript 中是否有同样优雅的方法来做到这一点。本质上是这样的数组:

[{quantity: 10}, {quantity: 20}, {quantity: 15}, ...]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有这样的事情,但我想知道它是否可以更短:

  orders.map((order)=>order.quantity).reduce((a, b)=> a+b,0);
Run Code Online (Sandbox Code Playgroud)

Ric*_*cky 5

您不需要使用map只需执行以下操作:

orders.reduce((a, b) => a + b.quantity, 0));
Run Code Online (Sandbox Code Playgroud)

orders.reduce((a, b) => a + b.quantity, 0));
Run Code Online (Sandbox Code Playgroud)

  • 使用 `reduce()` 方法时,应该知道,顾名思义,它会将您的数组减少为单个值。`accumulator + currentValue[property]` 的 `initialValue` 为 `0`。它对我来说非常易读`:P`。 (2认同)