JavaScript如果“ x =(a || b || c)”语句不起作用

Dar*_*ter 1 javascript if-statement logical-or

我正在用javascript开发一个简单的三角函数程序,并且if和while语句不能正常运行,因为它们仅在第一个条件为true时才通过,即如果您输入Sine,它将起作用,但如果您输入Cosine或Tangent,则不会。

<script language="JavaScript">
var opposite = 1
var adjacent = 1
var hypotenuse = 1
var sct = "SohCahToa"
while (!(sct == ("Sine" || "Cosine" || "Tangent"))) {
    sct = prompt("Sine (unknown adjacent) / Cosine (unkown opposite side) / Tangent (unknown hypotenuse)")
    if (!(sct == ("Sine" || "Cosine" || "Tangent"))) {
        alert("Spelling error, please try again")
    }
}
if (sct == ("Sine" || "Cosine"))
    hypotenuse = prompt("What is the hypotenuse")
if (sct == ("Sine" || "Tangent"))
    opposite = prompt("What is the opposite side")
if (sct == ("Tangent" || "Cosine"))
    adjacent = prompt("What is the adjacent side")
Run Code Online (Sandbox Code Playgroud)

谢谢(将代码另存为.html进行测试)

jfr*_*d00 5

您的所有多个比较如下所示:

if (sct == ("Sine" || "Cosine" || "Tangent"))
Run Code Online (Sandbox Code Playgroud)

需要更改为:

if (sct == "Sine" || sct == "Cosine" || sct == "Tangent")
Run Code Online (Sandbox Code Playgroud)

为了解释,当你做到这一点("Sine" || "Cosine" || "Tangent"),计算结果只"Sine"所以if (sct == ("Sine" || "Cosine" || "Tangent"))是一样的if (sct == "Sine"),这显然不是你想要的。


这是应用了所有更正的代码:

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")
Run Code Online (Sandbox Code Playgroud)