在 JS 中的数组中加法

我必须在javascript中做一个添加,使用如下数组:


[

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

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

{name: "toto",note: 5}

]

我想得到2 + 4 + 5 = 11(平均值更好,为3.6666)。


我尝试了.reduce,但我做不到。有什么帮助吗?谢谢


蓝山帝景
浏览 128回答 4
4回答

qq_笑_17

方式.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);

慕无忌1623718

相当短的代码    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);

潇潇雨雨

你也可以使用一个循环(在我的测试中,它比 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++){&nbsp; &nbsp; sum += a[i].note;}// sum = 11如果你想要平均值:let avg = sum / a.length;// avg = 3.6666~

守着一只汪

你可以试试:const arr = [&nbsp; {name: "toto",note: 2},&nbsp; {name: "titi",note: 4},&nbsp; {name: "toto",note: 5}]const result = arr.reduce((acc, { note }) => acc += note,0)console.log((result/arr.length).toFixed(4))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript