使用jQuery,我如何才能找到最匹配的一个数组,到指定号码 [英] using jquery, how would i find the closest match in an array, to a specified number
本文介绍了使用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屋!
查看全文