我想获得数组中最接近的数字。它必须是这样的:
例如我有一个数组: [1, 3, 7, 15, 40, 55, 70, 80, 95]
数字变量:numberD1
;
如果 numberD1: 8 - 最接近的数字只能是 7。不能是 15。
如果 numberD1: 54 - 只能是 40。不能是 55。
我的意思是,我想要这样最接近的数字。但我选择的数字不能高于最接近的数字(例如 Math.floor()
函数)。
抱歉我的英语不好。我希望我能很好地讲述我的问题。
最佳答案
你可以使用这个:
// sample array
a = [1, 3, 7, 15, 40, 55, 70, 80, 95]
// get right number
function getClosest(a, numberD1) {
return numberD1 - a.reduce(function(closest, v) {
return numberD1 >= v ? Math.min(numberD1-v, closest) : closest;
}, 1e100);
}
// output result
document.write(8 + ' => ' + getClosest(a, 8));
document.write('<br>');
document.write(54 + ' => ' + getClosest(a, 54));
关于javascript - 获取最接近的数组数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37219933/