如何在if语句中更改变量的值

时间:2016-10-28 20:38:01

标签: javascript function variables if-statement scope

<body>
<pre>

<form>
<strong> Height:</strong>      <input id ="Height"><br/>
<strong> Base: </strong>       <input id ="Base"><br/>
<strong> Hypotenus: </strong>  <input id ="Hypotenus"><br/>
</form>

<button type ="Button" onclick="Evaluate()">Find Area</button>
<p id ="Answer"> Answer will appear here </p>
<script>
function Evaluate() {
    var H = document.getElementById("Height").value;
    var B = document.getElementById("Base").value;
    var Hy = document.getElementById("Hypotenus").value;

    if (B == NaN || null) {
        var Area = Math.sqrt(Math.pow(Hy, 2) - Math.pow(H, 2));
    }
    document.getElementById("Answer").innerHTML = Area;
}
</script>
</body>

我是JavaScript的新手,我一直在努力创建一个找到三角形公式的代码。我的问题是在if语句之后我想改变“Area”的值,但每次运行代码时我都会得到undefined。如何在if语句中更改变量的值?

3 个答案:

答案 0 :(得分:1)

您的if()语句将始终为false,因此实际上您的Area变量永远不会被定义。更新语句如下:

if( isNaN(B) || null == B ) 
{
    var Area = Math.sqrt(Math.pow(Hy, 2) - Math.pow(H, 2));
}

您可能还希望在上面添加else块,否则document.getElementById("Answer").innerHTML = Area;可能会附加undefined

最后,您还需要更新变量定义,因为使用.value将始终返回一个字符串;您可以使用parseInt()parseFloat()

var H  = parseFloat( document.getElementById("Height"),
    B  = parseFloat( document.getElementById("Base").value ),
    Hy = parseFloat( document.getElementById("Hypotenus").value );

答案 1 :(得分:1)

这不是逻辑表达式在JavaScript中的工作方式,也不会为您提供预期的结果:

if (B == NaN || null) {

您必须进行两次单独的比较,并将它们与||结合使用:

if (B === NaN || B === null) {

除此之外,空输入不会有NaNnull值,而只是一个空字符串。您可能正在寻找此支票:

if (B.length === 0) {

或者,甚至更短:

if (!B) {

答案 2 :(得分:0)

除了别人所说的,而不是:

var Area = Math.sqrt(Math.pow(Hy, 2) - Math.pow(H, 2));

应该是:

var B = Math.sqrt(Math.pow(Hy, 2) - Math.pow(H, 2));
var area = B*H/2;