Javascript在数组中找不到最接近的数字

Amo*_*Amo 9 javascript

例如[300, 500, 700, 1000, 2000, 3000],我有一个数字数组,我想找到最接近的数字,而不是在给出的数字之下.

例如,搜索2200将返回3000(不是2000).

但是,如果我搜索3200,因为数组中没有更高的值,它应返回3000,因为没有其他选择.

我可以使用以下值获得最接近该值的数字:

if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
                sizeToUse = this;
            }
Run Code Online (Sandbox Code Playgroud)

但是,我无法完成所有工作.我的完整代码是:

$(function() {

var monitorWidth = window.screen.availWidth,
    sizeToUse = null,
    upscaleImages = false;

$('.responsive-img').each(function(){

    var sizeData = $(this).attr('data-available-sizes');
    sizeData = sizeData.replace(' ', '');

    var sizesAvailable = sizeData.split(',');
    sizesAvailable.sort(function(a, b){return b-a});

    $.each(sizesAvailable, function(){
        if(upscaleImages){
            if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
                sizeToUse = this;
            }
        }
        else{
            //We don't want to upscale images so we need to find the next highest image available
        }

    });

    console.log('Size to use ' + sizeToUse + ' monitor width ' + monitorWidth);

});


});
Run Code Online (Sandbox Code Playgroud)

Kar*_*non 6

您可以使用此代码:

function closest(arr, closestTo){

    var closest = Math.max.apply(null, arr); //Get the highest number in arr in case it match nothing.

    for(var i = 0; i < arr.length; i++){ //Loop the array
        if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i]; //Check if it's higher than your number, but lower than your closest value
    }

    return closest; // return the value
}

var x = closest(yourArr, 2200);
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/ngZ32/