Skip to content

undefined 变量

快速摘要

变量 exists 但 有 否 值 — 它 是 `undefined`, and using 它 as 如果 它 有 one causes problems.

为什么发生

  • Used 变量 之前 assigning 值 到 它

  • 变量 是 declared 但 从不 initialized

  • 函数 returned undefined and caller used result directly

最小示例

✗ 错误代码
let x;
console.log(x.length);
✓ 修复代码
let x = "";
console.log(x.length);

x 是 declared 但 从不 assigned, 所以 它 是 undefined — accessing .长度 on undefined throws TypeError.

如何诊断

  • Log 变量 值 正确 之前 行 那个 失败

  • Trace 哪里 变量 应该 有 是 assigned

  • 检查 如果 函数 or API call returned undefined

如何修复

  • Assign 值 到 变量 之前 using 它

  • Provide a default value (e.g., const name = input || 'guest')

  • 添加 guard 检查 之前 using 变量

如何预防

  • Initialize 变量 at 点 的 declaration

  • Use 默认 值 当 读取 从 APIs or 用户 输入

相关资源

相关术语

相关课程

相关练习

← 返回语言