如果陈述混合在一起

时间:2015-02-05 02:20:59

标签: javascript

我是JavaScript新手并尽我所能,所以请耐心等待我。我正在使用if else语句提出两个问题。

  1. 你居住的地方;
  2. 你在家多少小时。
  3. 根据答案houseapartment以及不到5小时的时间长短,他推荐一只宠物。

    我遇到的问题是如果我输入房子和> 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")
    }
    

    我希望这对我的要求有意义。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

存在轻微的逻辑问题:

residence == "House" || "house"

正在评估两个表达式

1:residence == "House"

2)"house"

"house"就是所谓的真理,意思是在测试时它将评估为真。因此,每当您调用此代码或其公寓对应时,它都会评估为真。

你应该写的是residence == "House" || 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")

}