gpt4 book ai didi

javascript - 用map方法求总数?

转载 作者:行者123 更新时间:2023-12-01 01:51:57 24 4
gpt4 key购买 nike

假设我有一些数据。

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

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

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

console.log(total);

关于javascript - 用map方法求总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51410571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com