且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-13 22:33:39

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