为了账号安全,请及时绑定邮箱和手机立即绑定

数组中对象的总和值

数组中对象的总和值

绝地无双 2023-03-10 13:34:09
试图从数组中的对象中求和我的值我有 3 个对象,在每个对象中都有两个字段,我在其中声明了值:let items = [       {        id: 1,         label: 'test',         itemname: 'testitem',         pieces: 4,        weight: 0.02      },      {        id: 2,         label: 'test',         itemname: 'testitem',         pieces: 4,        weight: 0.02      },      {        id: 2,         label: 'test',         itemname: 'testitem',         pieces: 4,        weight: 0.02      }    ];因此,如果我是正确的,则重量总和将为 0.06,而碎片总和将为 12,两者相乘将为 0.72,这意味着我想将重量总和与碎片总和相乘。我看到这样的例子:const weight = items.reduce((prev, cur) => {  return prev + (cur.weight * cur.pieces);}, 0);console.log(weight);在这个例子中,总和仅为 0.24。有人可以帮我吗编辑:@Robby Cornelissen 的评论是正确的。我的想法是错误的。
查看完整描述

2 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

如果您想要所有项目的总(总和)重量,您必须先获得每个项目的重量,然后将它们加在一起。


const sum = (arr) => {

    return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)

}

let items = [{

    id: 1,

    label: 'test',

    itemname: 'testitem',

    pieces: 4,

    weight: 0.02

  },

  {

    id: 2,

    label: 'test',

    itemname: 'testitem',

    pieces: 4,

    weight: 0.02

  },

  {

    id: 2,

    label: 'test',

    itemname: 'testitem',

    pieces: 4,

    weight: 0.02

  }

]


const sum = (arr) => {

  return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)

}


const totalWeight = sum(items)


console.log(totalWeight)


查看完整回答
反对 回复 2023-03-10
?
炎炎设计

TA贡献1808条经验 获得超4个赞

您可以使用forEach循环遍历数组,将pieces和weight值相加:


let pieces = 0; // sum of pieces

let weight = 0; // sum of weight

items.forEach(function(elmt){

    pieces += elmt.pieces;

    weight += elmt.weight;

});

然后乘以pieces* weight:


let total = pieces * weight;

console.log(total);


查看完整回答
反对 回复 2023-03-10
  • 2 回答
  • 0 关注
  • 219 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号