【问题标题】:Function to add values of array returns NaN添加数组值的函数返回 NaN
【发布时间】:2014-04-21 11:11:56
【问题描述】:

我有一个带有文本框的 HTML 表单,您可以在其中输入“1+2+8”之类的字符串,它会为您提供数字的总数。

我的脚本旨在添加数组“num”的所有数字并提醒该值。问题是警报显示 NAN 而不是总数。 num 中的值是浮点数,但警报仍然给出 NaN。 我看过this question,但这不是同一个问题。 这可能是什么原因造成的?

这里是 HTML/JS

<html>
  <head>
    <script type="text/javascript">


      function handleClick(event)
      {



        alert(this.textBox1.value);

        var num = this.textBox1.value.split("+"); 


        //convert string array to numbers
        for(var i=0; i<num.length; i++)
        {
            num[i] = +num[i]; 
        }

       // add up the values
        for(var i=0; i<num.length; i++)
        {
            var total = i + total;
        }
        alert(total); //Displays NaN instead of total



        event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
      function doit()
      {

        document.forms.myform.addEventListener("submit", handleClick, true);
        return true;
      }
    </script>
  </head>


  <body onload="doit()">
    <form name="myform">
      <div>
          <textarea name="textBox1" rows="10" cols="80">
1+1
         </textarea>
      </div>
      <input type="submit" value="Update"/>

    </form>
  </body>
</html>

【问题讨论】:

  • 在循环的第一次迭代中,i + total0 + undefined,即 NaN。因此,任何其他操作都会导致NaN。你必须用一个有意义的值初始化i

标签: javascript html


【解决方案1】:

在 for 循环外声明 total 变量并将其初始化为 0。您还必须访问数组中的实际值 (num[i]),而不是循环变量 (i)。

解决办法如下:

var total = 0;
for(var i=0; i<num.length; i++)
{
    total = num[i] + total;
}

【讨论】:

  • 这已经解决了 NaN 问题,但现在我得到了非常奇怪的结果,例如 5+5+5+5 = 6 和 5+5 = 1
  • @qwertie:您当然不想将循环变量 i 添加到结果中。
  • @FelixKling 我应该看到的。它应该是 num[i]
【解决方案2】:

尝试使用 parseFloat() 函数将其显式解析为浮动

例如

parseFloat("3.14");

您可以在以下位置阅读文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

【讨论】:

  • 我已尝试将其更改为“num[i] = parseFloat(i);”但这有同样的问题
【解决方案3】:

将字符串转换为整数时使用parseInt() 函数。还有parseFloat 支持非整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多