返回javascript中最接近匹配的数组项

时间:2013-11-28 16:55:49

标签: javascript jquery arrays

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

的一个非常接近的问题

但我需要逻辑方面的帮助。我想将值传递给getComparison,并返回最近的描述。

function getComparison(measure) {

    var key;
    var measures = [];
    measures[1]     = 'Height of Gloucester old spot pig';
    measures[2]     = 'Length of a racehorse';
    measures[3]     = 'Width of a cricket pitch';
    measures[4]     = 'Length of a salt water crocodile';
    measures[5]     = 'Length of a large family car';
    measures[6]     = 'Length of a Luton Van';
    measures[7]     = 'Height of Cheltenham War Memorial';
    measures[10]    = 'Length of a killer whale';
//etc
    var closest = null;
    jQuery.each(measures, function(){
        if (closest == null || Math.abs(this - measure) < Math.abs(closest - measure)) {
        closest = this;
        }
    });
    console.log(closest);
    return closest;
}

1 个答案:

答案 0 :(得分:2)

您需要比较长度,而不是字符串。

var closest = null;
var closest_dist;
$.each(measures, function(length) {
    var dist = Math.abs(length - measure);
    if (closest === null || dist < closest_dist) {
        closest = length;
        closest_dist = dist;
    }
});
return measures[closest];