在 JavaScript 中计算中位数
要在 JavaScript 中获取中位数,请使用 sort()
方法对整数数组进行排序。如果长度为奇数,则返回中点处的数字,如果长度为偶数,则返回数组中两个中间值的平均值。
在 JavaScript 中获取中位值
排序后的数字数组中的中间数字称为中位数。将根据数组中元素的数量选择中位数。
如果数组的长度为奇数
,则选择中间元素作为中位数。
list = [1, 2, 3]
len = 3
middleIndex = floor(len / 2); // 1
median = list[middleIndex]; // 2
如果列表的长度是偶数,则通过将中间元素与前一个元素相加并将结果除以 2 来选择中间元素。
list = [1, 2, 3, 4]
len = 4
middleIndex = floor(len / 2); // 2
median = (list[middleIndex] + list[middleIndex - 1]) / 2; // (3+2)/2 -> 2.5
median; // 2.5
示例下方是获取数字数组中位数的片段。
首先,我们创建 getSortedArray()
函数以从输入数组创建一个新的排序数组并将其返回。然后,创建一个函数 findMedian()
,它将返回数组的中位数。
例子:
function getSortedArray(arr) {
return arr.slice().sort((a, b) => a - b);
}
function findMedian(inputArray) {
let sortedArr = getSortedArray(inputArray);
let inputLength = inputArray.length;
let middleIndex = Math.floor(inputLength / 2);
let oddLength = inputLength % 2 != 0;
let median;
if (oddLength) { // if array length is odd -> return element at middleIndex
median = sortedArr[middleIndex];
} else {
median = (sortedArr[middleIndex] + sortedArr[middleIndex - 1]) / 2;
}
return median;
}
输出:
"findMedian([1,2,3]) => " 2
"findMedian([1,2,3,4,5,6]) => " 3.5
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。