Question

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();
Était-ce utile?

La 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/

Autres conseils

You forget to account for the case where the height is greater than ALL of your listed options.

if you run Math.max.apply(Math,[]) you will see it results in -Infinity. This means that your posb array is empty.

Here's my version: http://jsfiddle.net/pm7C3/

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 match = null,
        closest = -1,
        browsery = $(window).height();

    for (var i = 0; i < heights.length; i++) {
        var diff = Math.abs(browsery - heights[i]);
        if (closest == -1 || diff < closest) {
            closest = diff;
            match = heights[i];
        }
    }

    $(".area").css("height", match + "px");
    $(".area").css("width", "100%");
    $(".ground").css("background", "url(scenes/ground/" + match + ".png)");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top