【问题标题】:How does one change the value of a variable within an if statement如何在 if 语句中更改变量的值
【发布时间】:2016-10-28 20:38:00
【问题描述】:
<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 语句中更改变量的值?

【问题讨论】:

  • 首先,您首先使用适当的条件,如if ( B == NaN || B == null ),然后您意识到元素值将永远为 NaN 或 null,因为它始终是一个字符串.

标签: javascript function variables if-statement scope


【解决方案1】:

这不是逻辑表达式在 JavaScript 中的工作方式,并且不会给您预期的结果:

if (B == NaN || null) {

您必须进行两个单独的比较,然后将它们与|| 结合起来:

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

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

if (B.length === 0) {

或者,甚至更短:

if (!B) {

【讨论】:

    【解决方案2】:

    您的if() 语句将始终是错误的,因此实际上您的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 );
    

    【讨论】:

      【解决方案3】:

      除了别人说的,而不是:

      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;
      

      【讨论】:

      • 啊,我明白了。感谢您的信息
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      相关资源
      最近更新 更多