JavaScript if “x = (a || b || c)"声明不起作用 [英] JavaScript if "x = (a || b || c)" statement not working

查看:23
本文介绍了JavaScript if “x = (a || b || c)"声明不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 javascript 编写一个简单的三角程序,我的 if 和 while 语句不能正常工作,因为它们仅在第一个条件为真时才通过,即如果您输入 Sine 它将起作用,但如果您输入 Cosine 则不起作用或切线.

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 type in Sine it will work, but not if you type in Cosine or 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")

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

Thanks (save the code as a .html to test it)

推荐答案

所有看起来像这样的多重比较:

All your multiple comparisons that look like this:

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

需要改成这样:

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

<小时>

解释一下,当你这样做 ("Sine" || "Cosine" || "Tangent") 时,它的计算结果只是 "Sine" 所以 if (sct == ("Sine" || "Cosine" || "Tangent")) if (sct == "Sine") 一样,显然不是你想要什么.


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")

这篇关于JavaScript if “x = (a || b || c)"声明不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆