Fred Arnold Fred Arnold -3 years ago 87
Javascript Question

Syntax Required for If/Else Statement inside For Loop

I have a function that is applied onclick only when a specified variable is defined. Once that variable is defined, it loops through a set of nested arrays to produce a URL which the user is sent to. I added an else statement within the logic of the if statement so that if the condition is not met, the user is sent to a default URL which states, "sorry, no items found." However, since it is within a loop that is looping through items that don't match to find the one that does, it consistently applies the else statement before the loop finds the match.

Is there a better syntax to use?

function applyUrl() {

var locSelect = localStorage.getItem("loc");
var positSelect = localStorage.getItem("posit");
var userSelect = locSelect + " - " + positSelect;
if(localStorage.getItem("posit") != null){

for (var i = 0; i < sortedArray.length; i++) {
var stuff = sortedArray[i];
for (var j = 0; j < stuff.length; j++) {
if(stuff[j] === userSelect) {
window.location.href = stuff[1];
}else{
window.location.href = 'default.html';
}
}

}

}
}

Answer Source

I think the cleanest way is to just store a variable outside your for loop then navigate to it after your done, also only keep looping if you dont have a redirUrl yet.

function applyUrl() {

    var locSelect = localStorage.getItem("loc");
    var positSelect = localStorage.getItem("posit");
    var userSelect = locSelect + " - " + positSelect;
    if (localStorage.getItem("posit") != null) {
        var redirUrl;    
        for (var i = 0; i < sortedArray.length && !redirUrl; i++) {
            var stuff = sortedArray[i];
            for (var j = 0; j < stuff.length && !redirUrl; j++) {
                if (stuff[j] === userSelect) {
                    redirUrl = stuff[1];
                }
            }
        }

        window.location.href = redirUrl || 'default.html';
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download