使用jquery,我如何在数组中找到最接近的匹配到指定的数字
例如,你有一个这样的数组:
1,3,8,10,13,......
哪个数字最接近4?
4将返回3
2将返回3
5将返回3
6将返回8
我已经看过很多不同的语言,但不是jquery,这可以简单地做到吗
答案 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;