dimanche 24 mai 2015

Loops through Array executes "else" even when "if" statement is true (Javascript)

Simple question.. Not sure why this is happening...

Question: the "else" runs even when the if statement is true..

In this case...


The City entered is "Los Angelos" which is an array element of var "theAnswers" Meaning the alert should run and the program should finish...

What happens instead..


The program displays the else alert.. then displays the proper alert(if). See for yourself...

var theAnswers = ["New York City", "Chicago", "Los Angelos", "Cleveland", "Ohio", "Seattle", "Boston", "Miami", "Philadelphia"];

var userAnswer = prompt("I am thinking of a Major City.. guess which one it is?", "Los Angelos");
userAnswer = userAnswer.toLowerCase();

for (var i = 0; i < theAnswers.length; i++) {
    if (userAnswer === theAnswers[i].toLowerCase()) {
        alert("Good, your guess is correct. You get one point!");
        break;
    }

    else{
        alert("Hmm... not quite the City I was looking for... Better luck next time!");

    }
}

Aucun commentaire:

Enregistrer un commentaire