【问题标题】:using jquery, how would i find the closest match in an array, to a specified number使用 jquery,我将如何在数组中找到与指定数字最接近的匹配项
【发布时间】:2010-08-24 21:41:25
【问题描述】:

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

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

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

什么数最接近 4?

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

我见过很多不同的语言,但不是在 jquery 中,这可以简单地做到吗

【问题讨论】:

  • jQuery 是一个 JavaScript 库,用于简化 DOM 遍历和操作以及做 Ajax 的事情,而不是做数学。对于这种“普通”的 JavaScript 来说,它是非常合适的。你考虑过看看 JavaScript 吗?

标签: jquery arrays math rounding closest


【解决方案1】:

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

【讨论】:

  • 精彩,工作精美,感谢您如此快速的回复,以及干净的代码
  • 最好通过 closest === null 进行检查,否则 0 == null 也会返回 true。
  • @MarkusSiebeneicher:你从哪里得到这个结果?当我尝试(在 Firefox 中)时,0 == null 是错误的。
  • @Guffa:你说得对,我弄混了一些东西。在使用非严格变量类型编码多年后,我在编写 javascript 时有点偏执。无论如何,使用 === 进行显式类型检查是一种很好的做法。在这种情况下,真的没关系。感谢您指出。
  • 最接近的不是数字。当我在控制台Number {[[PrimitiveValue]]: 678} 中渲染最接近时,我得到了这个。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多