-
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++){ sum += a[i].note;}// sum = 11如果你想要平均值:let avg = sum / a.length;// avg = 3.6666~
-
守着一只汪
你可以试试: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))