Search code examples
javascriptloopsfor-loopclosestinfinity

Attempting to find closest number in array results in -Infinity JavaScript


I am trying to find the number that is the closest to another (the user's browser height) in an array and h is randomly -Infinity. Here is my code.

function match_height() {
    var heights = [11, 630, 693, 756, 819, 882, 945, 1008, 1071, 1134, 1197, 1260, 1323, 1386, 1449, 1512, 1575, 1638, 1701, 1764, 1827, 1890, 1953, 2016, 2079, 2142, 2205, 2268, 2331, 2394, 2457, 2520];
    var posb = [];

    var browsery = $(window).height();

    for (var i = 0; i < heights.length; i++) {
        if (browsery > heights[i] && heights[i + 1] <= browsery) {
            posb.push(heights[i+1]);
        }
    }

    var h = Math.max.apply(Math, posb);

    $(".area").css("height", h + "px");
    $(".area").css("width", "100%");
    $(".ground").css("background", "url(scenes/ground/" + h + ".png)");
}

match_height();

Solution

  • I think you want:

    if ( browsery > heights[i] && browsery <= heights[i+1] ) {
    

    In your current code, your posb array never gets populated with any value.


    Btw, consider this:

    var heights = [ ... ];
    var winHeight = $( window ).height();
    var i = 0;
    
    while ( winHeight > heights[i] ) i++;
    
    var h = heights[i];
    

    Live demo: http://jsfiddle.net/489La/