【问题标题】:Javascript NaN bugJavascript NaN 错误
【发布时间】:2016-06-27 19:54:47
【问题描述】:

这是我的 js 函数。当我输入数据时,我得到 NaN

//BMI is defined as BMI = ( Weight in Pounds / ( Height in inches x Height in inches ) ) x 703
function calculatebmi(weight, height){
    //window.alert("hello");
    var weight = parseInt(document.getElementsByName("weight_pounds"));
    var height = parseInt(document.getElementsByName("height_inches"));

    var bmi = parseInt(((weight/height)*703));
    window.alert("your BMI is: " + bmi);
}

我已经尝试过 math.floor 和 innerHTML。两者都没有帮助。

输入标签类型是数字,以防有人想知道。

【问题讨论】:

  • 您的 BMI 公式错误。你需要取高度的平方。
  • 哇。两个基本错误的独特组合,第一个是没有意识到 getElementsbyName 会产生一个节点列表,您必须采用第一个元素(为什么要使用名称而不是 ID?),第二个是不记得采用使用其value 属性的元素的值。

标签: javascript html nan


【解决方案1】:

尝试传递 parseInt 内部的值而不是节点对象,

 var weight = parseInt(document.getElementsByName("weight_pounds")[0].value);

如果您将对象传递给parseInt 而不是数字字符串,它将返回NaN。另外建议使用parseIntradix参数作为10,但是现在最近的浏览器默认将基数视为10。

请注意,getElementsByName 将返回一个 html 集合,因此您无法直接访问所需元素的值。您必须使用括号符号[0] 获取其第一个元素并访问其值。因此,为避免此类问题,您可以使用.querySelector(),如下所示,

 var weight = parseInt(document.querySelector("input[name='weight_pounds'])").value);

【讨论】:

    【解决方案2】:

    document.getElementsByName 返回NodeList

    您需要使用[0] 表示法从该集合中获取第一个元素,然后使用value 属性。

    var value = document.getElementsByName('weight_pounds')[0].value;
    var weight = parseInt(value, 10);
    

    对于parseInt函数radix(第二个参数)默认为10,但需要指定。 来自 MDN:

    始终指定此参数以消除读者混淆并保证可预测的行为。

    【讨论】:

      【解决方案3】:

      您正在尝试解析节点本身,而您应该尝试解析它们的值(使用 .value),并且您没有索引 getElementsByName 返回的集合:

      var weight = parseInt(document.getElementsByName("weight_pounds")[0].value);
      var height = parseInt(document.getElementsByName("height_inches")[0].value);
      

      【讨论】:

        猜你喜欢
        • 2014-04-30
        • 2013-06-15
        • 2017-01-01
        • 2014-03-25
        • 2011-07-03
        • 2017-10-10
        • 2012-10-04
        • 1970-01-01
        • 2013-08-12
        相关资源
        最近更新 更多