我不熟悉在 javascript 中使用哈希,并且想编写一个函数,它接受一个哈希数组并返回一个类的平均“等级”。这是一个例子:输入: {"string": "John", "integer": 7}, {"string": "Margot", "integer": 8}, {"string": "Jules", "integer": 4}, {"string": "Marco", "integer": 19} 输出:9.5提前致谢!
2 回答
qq_笑_17
TA贡献1818条经验 获得超7个赞
像平均值和求和这样的操作最好使用一个Array.prototype.reduce()操作来完成。
您可以使用reduce产生一个总和,然后将该结果除以数组长度
const arr = [
{"string": "John", "integer": 7},
{"string": "Margot", "integer": 8},
{"string": "Jules", "integer": 4},
{"string": "Marco", "integer": 19}
]
const avg = arr.reduce((sum, hash) => sum + hash.integer, 0) / arr.length
console.info(avg)
狐的传说
TA贡献1804条经验 获得超3个赞
let items = [
{"string": "John", "integer": 7},
{"string": "Margot", "integer": 8},
{"string": "Jules", "integer": 4},
{"string": "Marco", "integer": 19}
]
let avg = items.reduce((a, b) => a + b.integer, 0) / items.length
console.log(avg)
添加回答
举报
0/150
提交
取消
