www說
2023-03-24 15:30:10
我不熟悉在 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
提交
取消