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 に答える