使用jquery,我如何找到数组中最接近的匹配到指定的数字

时间:2010-08-24 21:41:25

标签: jquery arrays math rounding closest

使用jquery,我如何在数组中找到最接近的匹配到指定的数字

例如,你有一个这样的数组:

1,3,8,10,13,......

哪个数字最接近4?

4将返回3
2将返回3
5将返回3
6将返回8

我已经看过很多不同的语言,但不是jquery,这可以简单地做到吗

2 个答案:

答案 0 :(得分:39)

您可以使用jQuery.each方法循环数组,而不仅仅是普通的Javascript。类似的东西:

var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 4;
var closest = null;

$.each(theArray, function(){
  if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
    closest = this;
  }
});

答案 1 :(得分:0)

这是一个通用版本,取自:http://www.weask.us/entry/finding-closest-number-array

int nearest = -1;
int bestDistanceFoundYet = Integer.MAX_INTEGER;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
   // if we found the desired number, we return it.
   if (array[i] == desiredNumber) {
      return array[i];
   } else {
      // else, we consider the difference between the desired number and the current number in the array.
      int d = Math.abs(desiredNumber - array[i]);
      if (d < bestDistanceFoundYet) {
         // For the moment, this value is the nearest to the desired number...
         nearest = array[i];
      }
   }
}
return nearest;