10

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

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

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

最接近4的数是多少?

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

我看到这是用许多不同的语言完成的,但不是在 jquery 中,这可以简单地做到吗

4

2 回答 2

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;
  }
});
于 2010-08-24T21:48:42.077 回答
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;
于 2010-08-24T21:52:34.990 回答