关于javascript:使用map方法查找总数?

Using map method to find a total?

本问题已经有最佳答案,请猛点这里访问。

所以假设我有一些数据。

1
2
3
4
const cart = [
[{name:"Jose", total: 5}],
[{name:"Rich", total: 10}]
]

如何使用map或foreach合计这些合计?


How do I total up those totals using map or forEach?

The function Array.map() is to create new arrays applying a specific handler to each element. On the other hand, the function Array.forEach() could be a good approach to loop and sum the values.

最好的方法是使用函数reduce

假设该样本总是有一个带一个索引的数组。

1
2
3
4
const cart = [[{name:"Jose", total: 5}],[{name:"Rich", total: 10}]],
      total = cart.reduce((a, [{total} = [obj]]) => a + total, 0);
     
console.log(total);