NaN Result
快速摘要
你的 calculation resulted in `NaN` — 通常因为你 mixed 数字使用 `undefined`, 非-numeric 字符串, or other 无效值.
为什么发生
Parsed 非-numeric 字符串使用
parseInt()or数字()执行 arithmetic 使用
undefinedor 非-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); // 10parseInt("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
数字(值)orparseFloat()explicitly and 检查 resultProvide a default value (e.g.,
const n = parseInt(str) || 0)
如何预防
验证 numeric 输入 at 边界 (API, 用户输入)
Use
数字.isNaN()相反的 全局isNaN()到 avoid 类型 coercion
相关资源
相关课程
- 数据类型
学习关于 JavaScript 数据类型
相关练习
- JavaScript Primitive 类型
理解 primitive 类型 and 如何 NaN behaves.