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

为何我的BMI计算器代码返回NaN与Infinity?

修复BMI计算器的NaN与Infinity问题

问题根源

  1. NaN显示问题:未输入任何值就点击计算按钮时,输入框的值是空字符串,转为数字后是NaN,计算NaN / (NaN ** 2)结果仍为NaN,且代码先将NaN.toFixed(1)赋值给结果区域,之后才弹出提示,导致结果区残留错误值。
  2. Infinity显示问题:仅输入体重时,身高输入框为空转为0,weight / (0 ** 2)的计算结果是Infinity,同样因为先执行了结果赋值操作,导致错误值显示。

修复后的代码

JavaScript部分

const heightInput = document.querySelector(".height-input");
const weightInput = document.querySelector(".weight-input");
const result = document.querySelector(".result");
const statement = document.querySelector(".statement");

document.querySelector(".calculate").addEventListener("click", calculateButton);

function calculateButton() {
  // 清空上一次的结果与提示文本
  result.innerText = "";
  statement.innerText = "";

  // 处理输入格式:替换逗号为小数点,转为数字类型
  let height = parseFloat(heightInput.value.replace(",", "."));
  let weight = parseFloat(weightInput.value.replace(",", "."));

  // 前置校验输入有效性
  if (isNaN(height) || isNaN(weight) || height <= 0 || weight <= 0) {
    window.alert("Por favor, adicione informações válidas abaixo");
    return;
  }

  // 计算BMI值
  let BMI = weight / (height ** 2);
  result.innerText = BMI.toFixed(1);

  // 判断BMI对应的身体状态
  if (BMI < 18.5) {
    statement.innerText = "Você está abaixo do peso ideal. Consulte um médico para fechar um melhor diagnóstico.";
  } else if (BMI <= 24.9) {
    statement.innerText = "Seu IMC está dentro da normalidade.";
  } else if (BMI <= 29.9) {
    statement.innerText = "Você está com sobrepeso. Consulte um médico para fechar um melhor diagnóstico.";
  } else if (BMI <= 34.9) {
    statement.innerText = "Você está com obesidade grau I. Consulte um médico para fechar um melhor diagnóstico.";
  } else if (BMI <= 39.9) {
    statement.innerText = "Você está com obesidade grau II. Consulte um médico para fechar um melhor diagnóstico.";
  } else {
    statement.innerText = "Você está com obesidade grau III. Consulte um médico para fechar um melhor diagnóstico.";
  }
};

核心修复点

  • 前置输入校验:在计算BMI前先验证输入是否为有效数字,且身高、体重必须大于0,不满足条件直接提示并终止函数,避免无效计算。
  • 输入格式兼容:将输入中的逗号替换为小数点,适配葡语地区的数字输入习惯(如1,70转为1.70)。
  • 逻辑顺序调整:先清空旧结果,再校验输入,最后执行计算和DOM更新,从根源避免错误值提前显示。
  • 简化条件判断:移除冗余的下限判断(如BMI > 18.5可省略,因为前序条件已排除小于18.5的情况)。

额外优化建议

给输入框添加step="0.01"属性,支持小数输入:

<input class="height-input" id="height" name="height" type="number" placeholder="Ex: 1,70" required step="0.01">
<input class="weight-input" id="weight" name="weight" type="number" placeholder="Ex: 70" required step="0.01">

内容的提问来源于stack exchange,提问作者Rafael Lopes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:30:47