我对 JavaScript 很陌生,并且正在尽我所能,所以请耐心等待。我使用 if else
语句来问两个问题。
- 您居住的地方;
- 您在家工作了多少小时。
根据答案房子
或公寓
,以及少于5小时的时间,他推荐宠物。
我遇到的问题是,如果我输入 house 且 > 5 小时,它还会返回 > 5 小时的公寓选择。
这是我的代码:
var residence = prompt("Enter House, Apartment or Dorm");
var hours = prompt("Amount of hours home", "");
if ((residence == "House" || "house") && (hours <= 5)) {
var x=window.confirm("You should get a hamster" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
else if ((residence == "House" || "house") && (hours > 5) && (hours <= 10)) {
var x = window.confirm("You should get a cat" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
if ((residence == "Apartment" || "apartment") && (hours <= 5)) {
var x = window.confirm("You should get a gold fish" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
我希望这对我的要求有意义。感谢您的帮助。
最佳答案
有一个轻微的逻辑问题:
residence == "House" || "house"
正在计算两个表达式
1:住宅==“房子”
2) “房子”
"house"
就是所谓的“truthy”,这意味着在测试时它将评估为 true。因此,每次调用此代码或其对应的公寓代码时,它都会评估 true。
你应该写的是residence == "House"||住所==“房子”
。然而,有一种更简洁的方法来处理这个问题:
residence.toLowerCase() == "house"
您的新代码将如下所示:
var residence = prompt("Enter House, Apartment or Dorm");
var hours = prompt("Amount of hours home", "");
if (residence.toLowerCase() == "house" && (hours <= 5)) {
var x=window.confirm("You should get a hamster" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
else if (residence.toLowerCase() == "house" && (hours > 5) && (hours <= 10)) {
var x = window.confirm("You should get a cat" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
else if (residence.toLowerCase() == "apartment" && (hours <= 5)) {
var x = window.confirm("You should get a gold fish" + "\nWould you like to Purchase one?")
if (x)
window.alert("Thank you for your purchase!")
else
window.alert("Too bad")
}
关于javascript - if 语句混合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335125/