猿问

数组中对象的总和值

试图从数组中的对象中求和我的值


我有 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 的评论是正确的。我的想法是错误的。


绝地无双
浏览 220回答 2
2回答

拉丁的传说

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

炎炎设计

您可以使用forEach循环遍历数组,将pieces和weight值相加:let pieces = 0; // sum of pieceslet weight = 0; // sum of weightitems.forEach(function(elmt){    pieces += elmt.pieces;    weight += elmt.weight;});然后乘以pieces* weight:let total = pieces * weight;console.log(total);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答