Javascript 在中断之前,如何遍历该for循环中的所有城市?现在是';It’这只是一次迭代而已

Javascript 在中断之前,如何遍历该for循环中的所有城市?现在是';It’这只是一次迭代而已,javascript,arrays,for-loop,Javascript,Arrays,For Loop,我知道我的第一次突破陈述是在错误的地方,只是想说明我试图做的这个实践问题。如何让if语句在for循环中遍历数组中的所有城市?它只迭代第一个(我理解——它迭代一次,然后中断)。目标是迭代所有城市,然后在返回数组中的任何城市后中断 function cityInput(city) { var cityToCheck = prompt("Enter your city"); cityToCheck = cityToCheck.toLowerCase(); var cleanestCitie

我知道我的第一次突破陈述是在错误的地方,只是想说明我试图做的这个实践问题。如何让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();
功能城市输入(城市){
var cityToCheck=提示(“输入您的城市”);
cityToCheck=cityToCheck.toLowerCase();
var cleanestCities=[“夏延”、“圣达菲”、“图森”、“大瀑布”、“檀香山”];
对于(var i=0;i
如果阵列中的当前城市不是您要查找的城市,则您正在破坏。但是,下一个城市可能就是您要查找的城市。您应该做的是在得出此结论之前查看整个阵列。例如,您可以

var cleanestCities = ["cheyenne", "santa fe", "tucson", "great falls", "honolulu"];
var foundCity = false;
for (var i = 0; i <= 4; i++) {
    if (cityToCheck === cleanestCities[i]) {
        foundCity = true;
        break;
    }
}
if (foundCity) {
    alert("It's one of the cleanest cities");
} else {
    alert("city not listed");
}
或者
Array.prototype.some
,像这样

if (cleanestCities.indexOf(cityToCheck) !== -1) {
    alert("It's one of the cleanest cities");
} else {
    alert("city not listed");
}
if (cleanestCities.some(function(currentCity) {
    return currentCity === cityToCheck;
})) {
    alert("It's one of the cleanest cities");
} else {
    alert("city not listed");
}
使用ES6的箭头函数,您可以编写与

if (cleanestCities.some((currentCity) => currentCity === cityToCheck)) {
    alert("It's one of the cleanest cities");
} else {
    alert("city not listed");
}

只有在找到城市时,才能使用警报和中断的默认值

功能城市输入(城市){
var cityToCheck=提示(“输入您的城市”),
最清洁城市=[“夏延”、“圣达菲”、“图森”、“大瀑布”、“檀香山”],
msg=“城市未列出”;
cityToCheck=cityToCheck.toLowerCase();

对于(var i=0;i您不需要遍历所有城市,我认为这是一种过分的做法。您可以使用它并实现它,如下所示

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

    if (cleanestCities.indexOf(cityToCheck) >= 0) {
        alert("It's one of the cleanest cities");
    } else {
        alert("city not listed");
    }
}

cityInput();
函数cityInput(){
var cityToCheck=提示(“输入您的城市”);
cityToCheck=cityToCheck.toLowerCase();
var cleanestCities=[“夏延”、“圣达菲”、“图森”、“大瀑布”、“檀香山”];
对于(var i=0;i尝试该方法

localeCompare()
而不是

if语句中的运算符

应该看起来像这样:

if (cityToCheck.localeCompare(cleanestCities[i]))

兄弟,我把它放在那里是为了说明。这就是我要找的。清楚的回答。谢谢。
localeCompare()
if (cityToCheck.localeCompare(cleanestCities[i]))