javascript - 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.");
}
解决方案
问题是你的(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.");
}
推荐阅读
- css - 使用css从页脚隐藏URL
- python - Python POST 请求给出未知结果
- javascript - 在 Angular 中动态地将 src 分配给图像
- vue.js - 可以将桌面 PWA 设置为“始终在其他应用程序之上”吗?
- asp.net-core - 从 ASP.NET Core 2.2 升级到 3.0
- java - 试图在一个矩形内绘制文本,但在 android
- php - symfony 组件将数据附加到会话并破坏数据
- json - 发生异常 - 错误 JSON API - Flutter
- asp.net - 处理不同主机名的 Web 表单应用程序
- perl - Perl s/$array[1]\b/$array[1] 不会替换