亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

數組中對象的總和值

數組中對象的總和值

絕地無雙 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 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號