要取得平均值,我们需要将数字求和,然后除以 values
的长度,步骤如下:
- 取得数组长度(
length
) - 求和(
sum
) - 取得平均值(
sum/length
)
let values = [44, 56, 3, 66, 10, 4, 100, 23]
const avg = (arr) => {
let len = arr.length
let total = arr.reduce((prev, cur) => (cur += prev))
return (total /= len)
}
console.log(avg(values)) // 38.25
取得中位数的步骤是:
- 将数组排序
- 取得中位数
let values = [44, 56, 3, 66, 10, 4, 100, 23]
const median = (arr) => {
arr.sort((a, b) => a - b)
let lowMiddle = Math.floor((arr.length - 1) / 2)
let highMiddle = Math.ceil((arr.length - 1) / 2)
return (arr[lowMiddle] + arr[highMiddle]) / 2
}
console.log(median(values)) // 33.5
或者使用无符号右移操作符:
let values = [44, 56, 3, 66, 10, 4, 100, 23]
const median = (arr) => {
arr.sort((a, b) => a - b)
return (arr[(arr.length - 1) >> 1] + arr[arr.length >> 1]) / 2
}
console.log(median(values)) // 33.5