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
相关产品推荐
相关产品推荐

