node.js - 使用reduce查找数组内的对象总和
问题描述
我试图从数组中的对象中找到总数,每个对象都有一个价格和数量,当数组正好有两个对象时,我可以找到总数,但它产生的对象超过两个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函数中所示,第二个参数输入
推荐阅读
- cucumber - Webdriver-IO 测试以时间成本 onPrepare 钩子开始
- jenkins - 在 Jenkins 中显示 Terraform Plan 输出的好方法
- python - ValueError: y 应该是一维数组,得到一个形状为 (5024, 2) 的数组
- awk - awk 按最后一列排序并打印整行
- reactjs - 我可以在反应中找到 ref 对象内的元素吗?
- php - 分页自定义 SQL 查询
- javascript - fabric js:将 fabric.Group 导出到DataUrl
- javascript - 使用实时媒体流作为参与者语音而不是 getUserMedia:Twilio Video
- javascript - 尝试将项目添加到数据库时jquery ajax动画不起作用
- pentaho - 来自 URL 的 pentaho 登录用户名