2 回答
TA貢獻1818條經驗 獲得超7個贊
像平均值和求和這樣的操作最好使用一個Array.prototype.reduce()操作來完成。
您可以使用reduce產生一個總和,然后將該結果除以數(shù)組長度
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)
添加回答
舉報
