我知道我的第一个break语句在错误的位置,只是想说明一下我正在尝试解决此实践问题。如何获得if语句在for循环内遍历数组中的所有城市?它只是迭代第一个(据我所知-它迭代一次,然后中断)。目标是遍历所有城市,然后在返回阵列中的任何城市后中断。

function cityInput(city) {
  var cityToCheck = prompt("Enter your city");
  cityToCheck = cityToCheck.toLowerCase();
  var cleanestCities = ["cheyenne", "santa fe", "tucson", "great falls", "honolulu"];
  for (var i = 0; i <= 4; i++) {
    if (cityToCheck === cleanestCities[i]) {
      alert("It's one of the cleanest cities");
      break;
    } else {
      alert("city not listed");
      break;
    }
  }
};

cityInput();

最佳答案

您可以为警报使用默认值,并且仅在找到城市时才中断。



function cityInput(city) {
    var cityToCheck = prompt("Enter your city"),
        cleanestCities = ["cheyenne", "santa fe", "tucson", "great falls", "honolulu"],
        msg = "city not listed";

    cityToCheck = cityToCheck.toLowerCase();
    for (var i = 0; i <= 4; i++) {
        if (cityToCheck === cleanestCities[i]) {
            msg = "It's one of the cleanest cities";
            break;
        }
    }
    alert(msg);
};

cityInput();

10-08 01:24