Skip to content

NaN Result

快速摘要

你的 calculation resulted in `NaN` — 通常因为你 mixed 数字使用 `undefined`, 非-numeric 字符串, or other 无效值.

为什么发生

  • Parsed 非-numeric 字符串使用 parseInt() or 数字()

  • 执行 arithmetic 使用 undefined or 非-numeric 值

  • 划分零 通过零 (0 / 0) or took square 根的 负数字

最小示例

✗ 错误代码
const result = 10 + parseInt("abc");
console.log(result); // NaN
✓ 修复代码
const n = parseInt("abc") || 0;
const result = 10 + n;
console.log(result); // 10

parseInt("abc") returns NaN, and 10 + NaN is NaN — use || 0 to fall back to 0 when parsing fails.

如何诊断

  • Log 每个 operand 到查找哪个 one 是不 数字

  • Use 数字.isNaN() 到检查如果值 是 NaN (不全局 isNaN)

  • Trace 哪里非-numeric 值输入 calculation

如何修复

  • 验证输入是 数字之前执行 arithmetic

  • Use 数字(值) or parseFloat() explicitly and 检查 result

  • Provide a default value (e.g., const n = parseInt(str) || 0)

如何预防

  • 验证 numeric 输入 at 边界 (API, 用户输入)

  • Use 数字.isNaN() 相反的 全局 isNaN() 到 avoid 类型 coercion

相关资源

相关术语

相关课程

相关练习

← 返回语言