首页 > 解决方案 > JavaScript IF 条件有意外结果

问题描述

我是一个完整的初学者,试图用我在一天的 Javascript 中学到的东西制作一个快速的基于文本的东西。为什么这段代码不能通过第一个 IF 条件?如果我输入“是”以外的任何内容,它仍然会显示“哇哦!” 我已经尝试过 else if 语句和所有内容,但我无法弄清楚。

感谢您指出我的错误。

var firstName = prompt("What's your first name?");
var lastName = prompt("Ooo I like that. So, what's your last name?");

var answer = prompt(firstName + " " + lastName + ", huh? Wow, I love that name! I'm a little bored right now...so, would you like to play a Choose Your Own Adventure Game?");

if (answer === "yes" || "Yes") {
    alert("Woohoo! I haven't played this in a long time. Okay, here goes. Press the OK button to start.");
} 
else {
    alert("Oh, okay. Well, I'll see you later.");
}

标签: javascript

解决方案


问题是你的(answer === "yes" || "Yes")条件......"Yes"总是评估为true(在Javascript中),所以你基本上是在说'回答===“是”还是真的'......这总是正确的。要更正逻辑,您应该使用(answer === "yes" || answer === "Yes")

我会规范化输出(并检查响应),这样你就可以检查一个条件......

var firstName = prompt("What's your first name?");
var lastName = prompt("Ooo I like that. So, what's your last name?");

var answer = prompt(firstName + " " + lastName + ", huh? Wow, I love that name! I'm a little bored right now...so, would you like to play a Choose Your Own Adventure Game?");

if (answer && answer.toLowerCase() === "yes") {
    alert("Woohoo! I haven't played this in a long time. Okay, here goes. Press the OK button to start.");
} 
else {
    alert("Oh, okay. Well, I'll see you later.");
}


推荐阅读