使用 jquery,我如何在数组中找到与指定数字最接近的匹配项 [英] using jquery, how would i find the closest match in an array, to a specified number

查看:24
本文介绍了使用 jquery,我如何在数组中找到与指定数字最接近的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

using jquery, how would i find the closest match in an array, to a specified number

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

For example, you've got an array like this:

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

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

哪个数字最接近 4?

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

4 would return 3
2 would return 3
5 would return 3
6 would return 8

我在许多不同的语言中看到过这个,但在 jquery 中没有,这是否可以简单地做到

ive seen this done in many different languages, but not in jquery, is this possible to do simply

推荐答案

您可以使用 jQuery.each 方法来循环数组,除此之外,它只是简单的 Javascript.类似的东西:

You can use the jQuery.each method to loop the array, other than that it's just plain Javascript. Something like:

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;
  }
});

这篇关于使用 jquery,我如何在数组中找到与指定数字最接近的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆