Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery,如何在数组中找到与指定数字最接近的匹配项_Jquery_Arrays_Math_Rounding_Closest - Fatal编程技术网

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

使用jquery,如何在数组中找到与指定数字最接近的匹配项,jquery,arrays,math,rounding,closest,Jquery,Arrays,Math,Rounding,Closest,使用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; $.e

使用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;
  }
});
var theArray=[1,3,8,10,13];
var目标=4;
var=null;
$.each(数组,函数(){
if(最接近==null | | Math.abs(本目标)
以下是一个通用版本,摘自:

int最近值=-1;
int bestdistance foundyet=Integer.MAX\u Integer;
//我们在数组上迭代。。。
for(int i=0;i
jQuery是一个JavaScript库,用于简化DOM遍历和操作,并进行Ajax操作,而不是进行数学运算。对于这种“普通的”JavaScript是非常合适的。你考虑过看JavaScript吗?太棒了,工作得很好,谢谢你这么快的回复,干净的代码最好用最近的===null检查,否则0==null也会返回true。@MarkusSiebeneicher:你从哪里得到这个结果的?当我(在Firefox中)尝试时,
0==null
是错误的。@Guffa:你说得对,我弄错了什么。在使用非严格变量类型编写了多年之后,我在编写javascript时有点偏执。无论如何,最好使用===进行显式类型检查。在这种情况下,这真的无关紧要。谢谢你指出。最近的不是数字。。当我在控制台
Number{[[PrimitiveValue]]:678}
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;