JavaScript if “x = (a || b || c)” statement not working

后端 未结 2 1662
既然无缘
既然无缘 2020-11-27 23:12

I am making a simple trigonometry program in javascript and my if and while statements are not working properly, as they only pass if the first condition is true i.e. if you

2条回答
  •  迷失自我
    2020-11-28 00:00

    All your multiple comparisons that look like this:

    if (sct == ("Sine" || "Cosine" || "Tangent"))
    

    need to be changed to this:

    if (sct == "Sine" || sct == "Cosine" || sct == "Tangent")
    

    To explain, when you do this ("Sine" || "Cosine" || "Tangent"), that evaluates to just "Sine" so if (sct == ("Sine" || "Cosine" || "Tangent")) is the same as if (sct == "Sine") which is obviously not what you want.


    Here is your code with all the corrections applied:

    var opposite = 1
    var adjacent = 1
    var hypotenuse = 1
    var sct = "SohCahToa"
    while (!(sct == "Sine" || sct == "Cosine" || sct == "Tangent")) {
        sct = prompt("Sine (unknown adjacent) / Cosine (unkown opposite side) / Tangent (unknown hypotenuse)")
        (!(sct == "Sine" || sct == "Cosine" || sct == "Tangent")) {
            alert("Spelling error, please try again")
        }
    }
    if (sct == "Sine" || sct == "Cosine")
        hypotenuse = prompt("What is the hypotenuse")
    if (sct == "Sine" || sct == "Tangent")
        opposite = prompt("What is the opposite side")
    if (sct == "Tangent" || sct == "Cosine")
        adjacent = prompt("What is the adjacent side")
    

提交回复
热议问题