为了账号安全,请及时绑定邮箱和手机立即绑定

在 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条经验 获得超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))


查看完整回答
反对 回复 2022-09-29
  • 4 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信