这是一个关闭的问题using jquery, how would i find the closest match in an array, to a specified numberjavascript中最接近匹配的返回数组项目
但我需要帮助的逻辑。我想传递一个值给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;
}
...这是一个笑话,对吧? – JJJ
规模数字似乎不见了,或者是1-10呢?它们应该像那样是线性的吗? – Halcyon
不,它是零星的,因为没有完整的长度列表,即没有匹配的8米或9米长度,所以我想返回最近的。 – Jeepstone