有两个数组num1 = [1,2,3],num2 = [5,4,7],求他们中位数是多少?
function fn(num1,num2){
let res = 0;
let newArr = num1.concat(num2).sort((a, b) => {
return a - b
});
let length = newArr.length
if(length % 2){
res = newArr[Math.floor(length/2)]
return res.toFixed(1)
}else {
res = (newArr[Math.floor(length/2)-1] +newArr[Math.floor(length/2)])/2
return res.toFixed(1)
}
}
fn([1,2,3],[5,4,7])
总结:首先定义一个初始值res用来存放两个数组的值,其次将num2添加到num1中,然后在把新数组进行排序,最后使用Math.floor()对值进行向下取整,使用res.toFixed()将到的值四舍五入。