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

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

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

1,3,8,10,13 ……

什么数字最接近4?

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

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

你可以使用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; } }); 

这是一个通用版本,取自: 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;