lundi 17 juin 2019

how to make this loop only write the second if once when all no matches are found

I have an array of 5 cities that are the cleanest in my country. So I put them in an array. Then there's a prompt where a user has to enter their city and if the city is found in the array, a message prints out "wooray".

If the city isn't found a message prints out "your city stinks".

Since the names of the 5 clean cities are in an array, I made a for loop to go through all the names and compare to find a match.

Its working, however if that is the third item, the user will still get

"Your city stinks"

"Your city stinks"

"Wooray "

Then only then will the loops break. I need to only send "wooray" without the "stinks" and only send the "stinks" when it has been confirmed to the end of the array that the city isn't there.

var cityToCheck = prompt("your humble city?");

var cleanestCities = ["Bulawayo", "gweru", "Gwanda", "falls", "plumtree"];

var found = "no";

for (var i = 0; i < 5; i++) {

  if (cityToCheck == cleanestCities[i]) {
    found = "yes";
    console.log("wooray");
    break;
  };

  if (found = "no") {
    console.log("your city    stinks");
  }
}

Aucun commentaire:

Enregistrer un commentaire