我知道我的第一个中断语句在错误的地方,只是想说明我试图用这个练习题做什么。 如何让 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();
} else {
alert("city not listed");
break;
}
如果数组中的当前城市不是您要查找的城市,则正在中断。但是,下一个城市可能是您正在寻找的城市。在得出此结论之前,您应该做的是查看整个数组。例如,你可以做
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.indexOf
函数并像这样编写整个函数
if (cleanestCities.indexOf(cityToCheck) !== -1) {
alert("It's one of the cleanest cities");
} else {
alert("city not listed");
}
或者Array.prototype.some
,像这样
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");
}
你不需要遍历所有城市,我相信这是矫枉过正。你可以只使用Array.indexOf并实现它,如下所示...
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();
function cityInput() {
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");
return;
}
}
alert("city not listed");
};
这应该做到
尝试该方法
localeCompare()
而不是
===
if 语句中的运算符。
应该看起来像这样:
if (cityToCheck.localeCompare(cleanestCities[i]))