4 回答
![?](http://img1.sycdn.imooc.com/5859e2d50001f6bb01000100-100-100.jpg)
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);
![?](http://img1.sycdn.imooc.com/5458620000018a2602200220-100-100.jpg)
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);
![?](http://img1.sycdn.imooc.com/54584d080001566902200220-100-100.jpg)
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~
![?](http://img1.sycdn.imooc.com/54586653000151cd02200220-100-100.jpg)
TA贡献1872条经验 获得超3个赞
你可以试试:
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))
添加回答
举报