Javascript在不进入的情况下找到数组中最接近的数字

标签 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;
            }

但是,我无法使整个过程正常运行。我的完整代码是:

$(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);

});


});

最佳答案

您可以使用此代码:

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);

fiddle :http://jsfiddle.net/ngZ32/

关于Javascript在不进入的情况下找到数组中最接近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25061543/

相关文章:

javascript - 如何在 Phoenix 中使用 d3.js?

javascript - Rails 3.1 http streaming - js 在头部或 body 底部?

javascript - 根据另一个填充 1 个表单域

javascript - 尝试使用 MSE 播放 webm 时出错, block 未附加,视频停止

javascript - 从数组中获取日期值并将其设置到电子表格中的单元格中

javascript - SailsJS 将对象/变量传递给布局 View 的正确方法

javascript - 从模态对话框 : Javascript 访问父 Windows URL

javascript - 如何设置扩展菜单在页面加载时关闭

javascript - 如何使用javascript格式化日期字符串

javascript - AngularJS + ngTable + plunker 将无法正确呈现表格