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

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

在 JS 中的數組中加法

在 JS 中的數組中加法

藍山帝景 2022-09-29 10:25:03
我必須在javascript中做一個添加,使用如下數組:[{name: "toto",note: 2},{name: "titi",note: 4},{name: "toto",note: 5}]我想得到2 + 4 + 5 = 11(平均值更好,為3.6666)。我嘗試了.reduce,但我做不到。有什么幫助嗎?謝謝
查看完整描述

4 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

方式.reduce()


let data = [

{name: "toto",note: 2},

{name: "titi",note: 4},

{name: "toto",note: 5}

]


let result = data.reduce((a,v) => v.note + a, 0);


console.log(result);


查看完整回答
反對 回復 2022-09-29
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

相當短的代碼


    const data = [

        { name: "toto", note: 2 },

        { name: "titi", note: 4 },

        { name: "toto", note: 5 }

    ];

    const average = data.reduce((a, { note }) => {

        return a + note;

    }, 0) / data.length;

    console.log(average);


查看完整回答
反對 回復 2022-09-29
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

你也可以使用一個循環(在我的測試中,它比 reduce()快50%)來構建總和:


let a = [

{name: "toto",note: 2},

{name: "titi",note: 4},

{name: "toto",note: 5}

];


let sum = 0;

for(var i=0; i< a.length; i++){

    sum += a[i].note;

}


// sum = 11

如果你想要平均值:


let avg = sum / a.length;

// avg = 3.6666~


查看完整回答
反對 回復 2022-09-29
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

你可以試試:


const arr = [

  {name: "toto",note: 2},

  {name: "titi",note: 4},

  {name: "toto",note: 5}

]


const result = arr.reduce((acc, { note }) => acc += note,0)


console.log((result/arr.length).toFixed(4))


查看完整回答
反對 回復 2022-09-29
  • 4 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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