即使“if”语句为真,循环遍历Array也会执行“else”(Javascript)

时间:2015-05-24 08:52:25

标签: javascript arrays loops if-statement

简单的问题..不确定为什么会发生这种情况......

问题:即使 if 语句为true,“ else ”也会运行。

在这种情况下......

进入的城市是“Los Angelos”,这是var“theAnswers”的数组元素 意味着警报应该运行,程序应该完成......

反而会发生什么......

程序显示else警报..然后显示正确的警报(如果)。 亲眼看看......

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!");

    }
}

3 个答案:

答案 0 :(得分:2)

那是因为您在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!");
}

答案 1 :(得分:1)

删除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!");
}

Fiddle

答案 2 :(得分:0)

它实际上并没有执行&#34; else&#34;当条件成立时。

if (userAnswer === theAnswers[i].toLowerCase())

第一次评估这个条件时,我是0,所以答案[i]是&#34;纽约市&#34;。