JavaScript IF条件发生意外结果

时间:2018-07-18 03:12:49

标签: javascript

我是一个完整的初学者,试图用我一天在Javascript中学到的东西来做快速的基于文本的事情。为什么此代码不能超过第一个IF条件?如果我输入的不是“是”,它仍然显示“ woohoo!”。我尝试了if语句和其他所有功能,但我无法弄清楚。

感谢您指出我的错误。

2^f(n) = O(2^g(n))

3 个答案:

答案 0 :(得分:2)

问题是您的(answer === "yes" || "Yes")条件... "Yes"总是计算为true(用Java语言编写),因此您基本上是说'确实回答===“是”或正确” ...这始终是正确的。要更正逻辑,您应该使用(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.");
}

答案 1 :(得分:0)

非空字符串(例如字符串'Yes')始终是真实的,因此if (answer === "yes" || "Yes") {将始终取值为if (true)。如果要检查答案是yes还是Yes,可以将它们放入数组并使用.includes

const yesArr = ['yes', 'Yes'];
console.log(yesArr.includes('Yes'));
console.log(yesArr.includes('No'));

或者如果大写字母根本不重要,请先将字符串转换为小写,然后检查:

console.log('YES'.toLowerCase() === 'yes')

或者您可以使用不区分大小写的正则表达式:

console.log(/yes/i.test('YES'))

答案 2 :(得分:0)

只需更正您的if条件,它应该为

if (answer || answer.toLowerCase() === "yes") {
//dosomething
}

它将检查两个值的答案(“是”和“是”)。