![](/img/trans.png)
[英]Loops through Array but executes “else” statement even when “if” statement is true (javascript)
[英]Loops through Array executes “else” even when “if” statement is true (Javascript)
一個簡單的問題..不確定為什么會這樣...
問題:即使if語句為true,“ else ”也會運行。
在這種情況下...
輸入的城市為“ Los Angelos”,它是變量“ theAnswers”的數組元素,表示應運行警報,程序應完成...
會發生什么。
程序顯示else警報。然后顯示正確的警報(if)。 你自己看...
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!");
}
}
這是因為您在進行else
每項檢查時else
在else
中顯示該消息。 它將顯示每個不匹配的城市的消息。 首先瀏覽所有城市,然后一次顯示結果:
var found = false;
for (var i = 0; i < theAnswers.length; i++) {
if (userAnswer === theAnswers[i].toLowerCase()) {
found = true;
break;
}
}
if (found) {
alert("Good, your guess is correct. You get one point!");
}else{
alert("Hmm... not quite the City I was looking for... Better luck next time!");
}
刪除for循環。 您不必遍歷數組就可以知道答案是否存在,只要知道它的位置就足夠了。 嘗試這個:
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");
if (theAnswers.indexOf(userAnswer)>=0) {
alert("Good, your guess is correct. You get one point!");
}else{
alert("Hmm... not quite the City I was looking for... Better luck next time!");
}
條件為真時,它實際上不執行“其他”。
if (userAnswer === theAnswers[i].toLowerCase())
第一次評估此條件時,i為0,因此Answers [i]為“紐約市”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.