let values = [2, 56, 3, 41, 0, 4, 100, 23]; let sum = values.reduce((previous, current) => current += previous); let avg = sum / values.length; // avg = 28
或者:
1 2 3 4 5
let values = [2, 56, 3, 41, 0, 4, 100, 23]; let count = values.length; values = values.reduce((previous, current) => current += previous); values /= count; // avg = 28
中位数
现在,要获取中位数步骤为:
对数组排序
得到中间值的等值均值
1 2 3 4 5 6
let values = [2, 56, 3, 41, 0, 4, 100, 23]; values.sort((a, b) => a - b); let lowMiddle = Math.floor((values.length - 1) / 2); let highMiddle = Math.ceil((values.length - 1) / 2); let median = (values[lowMiddle] + values[highMiddle]) / 2; // median = 13,5
使用按位运算符:
1 2 3 4
let values = [2, 56, 3, 41, 0, 4, 100, 23]; values.sort((a, b) => a - b); let median = (values[(values.length - 1) >> 1] + values[values.length >> 1]) / 2 // median = 13,5