You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript BMI计算器输出NaN问题求助:无法获取有效数值

BMI计算器NaN问题排查与修复

问题根源

  • 过早获取输入值:页面刚加载就读取输入框的value,此时输入为空,得到的是空字符串,直接参与计算会生成NaN。同时函数参数与外部变量重名,调用时若未传值,参数会是undefined,进一步导致计算异常。
  • BMI公式错误:正确公式是体重(kg) ÷ (身高(m))²,你写成了heightinm*2,逻辑错误直接导致结果无效。
  • 未定义变量引用:第二个条件判断里用了未声明的o,应该是output。
  • 字符串未转数字:输入框的value是字符串类型,直接运算会触发错误的隐式类型转换。

修复后的代码

function bmival() {
    // 调用时才获取输入值并转为数字
    const weightkg = parseFloat(document.getElementById('weight').value);
    const heightinm = parseFloat(document.getElementById('height').value);

    // 校验输入有效性
    if (isNaN(weightkg) || isNaN(heightinm) || heightinm <= 0) {
        document.getElementById('print').innerHTML = "请输入有效的体重和身高数值";
        return;
    }

    // 正确计算BMI
    const hout = heightinm ** 2; // 等价于heightinm * heightinm
    let output = weightkg / hout;
    output = output.toFixed(2); // 保留两位小数,结果更直观

    if (output <= 18.5) {
        document.getElementById('print').innerHTML = `Your BMI is ${output} you are underweight`;
    } else if (output > 18.5 && output < 25.5) {
        document.getElementById('print').innerHTML = `Your BMI is ${output} You come under fit category`;
    } else {
        document.getElementById('print').innerHTML = `Your BMI is ${output} you are overweight and obese`;
    }
}

额外优化提示

  • 给输入框设置type="number",限制用户只能输入数字,降低无效输入概率。
  • 绑定按钮点击事件或输入框的change事件来触发bmival函数,确保用户输入完成后再计算。
  • 修正拼写错误:catogery改为category。

内容的提问来源于stack exchange,提问作者Ayush panwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:42:22