gpt4 book ai didi

node.js - 使用reduce求数组内对象的总和

转载 作者:太空宇宙 更新时间:2023-11-03 23:13:26 25 4
gpt4 key购买 nike

我正在尝试查找数组内对象的总数,每个对象都有一个价格和数量,当数组恰好有两个对象时,我可以找到总数,但对于两个以上的对象,它会产生 NaN

arr = [ { quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 } ]


const reducer = (accumulator, currentValue) => {
var a = accumulator.quantity * accumulator.price;
var b = currentValue.quantity * currentValue.price;
return a + b;
}
console.log(arr.reduce(reducer)); // sum if array contains 2 objects, NaN otherwise.

最佳答案

    let arr = [ 
{ quantity: 1, price: 30 },
{ quantity: 1, price: 40 },
{ quantity: 2, price: 10 },
{ quantity: 1, price: 10 }
]

let reducer = (acc, cur) => {
return acc + (Number(cur.quantity) * Number(cur.price));
};

console.log(arr.reduce(reducer, 0));
// 100

你的减速函数似乎是错误的。累加器不再有任何参数,因为它累加 - 它是一个整数。另外,为累加器设置一个初始值以开始累加,如reduce函数第二个参数输入所示

关于node.js - 使用reduce求数组内对象的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508952/

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