JavaScript Array reduce 方法

JavaScript About 610 words

计算总数

初始值为基础类型。

方法一

const arr = [
    {amount: 19.9, name: "product a"},
    {amount: 29.9, name: "product b"},
    {amount: 39.9, name: "product c"},
];
const total = arr.reduce((acc, cur) => {
    acc += cur.amount;
    return acc
}, 0);
console.log(total);

输出

89.69999999999999

方法二

初始值为引用类型(对象)。

const arr = [
    {amount: 19.9, name: "product a"},
    {amount: 29.9, name: "product b"},
    {amount: 39.9, name: "product c"},
];
const obj = arr.reduce((acc, cur) => {
    acc.total += cur.amount;
    return {total: acc.total}
}, {
    total: 0
});
console.log(obj);

输出

{
    "total": 89.69999999999999
}
Views: 9 · Posted: 2025-11-30

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh