如何确定我的号码最接近哪个数组索引? [英] How can I determine which array index my number is closest to?
本文介绍了如何确定我的号码最接近哪个数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数组和变量:
I have an array and var that look like this:
var paymentMilestones = [0, 30, 60, 90];
var daysOverdue = 33;
在 JavaScript 中,如何以编程方式确定 daysOverdue
变量最接近哪个 paymentMilestones
索引?我需要返回那个值,所以在这种情况下,函数应该返回 30
.
In JavaScript, how can I programmatically determine which of the paymentMilestones
indexes the daysOverdue
var is closest to? I need that value returned, so in this case the function should return 30
.
推荐答案
快速回答(如果有平局,它将带回两者 - 假设数组已预先排序):
A quick answer (if there is a tie it will bring back both - assuming the array is pre-sorted):
var paymentMilestones = [0, 30, 60, 90];
var daysOverdue = 33;
function findClose(array,elem){
var minDelta = null;
var minIndex = null;
for (var i = 0 ; i<array.length; i++){
var delta = Math.abs(array[i]-elem);
if (minDelta == null || delta < minDelta){
minDelta = delta;
minIndex = i;
}
else if (delta == minDelta) {
return [array[minIndex],array[i]];
}
// unchecked: stop if delta starts becoming bigger again
else {
return [array[i-1]];
}
}
return array[minIndex];
}
var closest = findClose(paymentMilestones,daysOverdue);
这篇关于如何确定我的号码最接近哪个数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文