ReferenceError: x 是不 定义
错误信息
x 是不 定义
快速摘要
你 referenced 变量 name 那个 JavaScript doesn't know 关于 — 它是 从不 declared 使用 `let`, `const`, or `var` in 任何 accessible 作用域.
为什么发生
Typo in 变量 name
Forgot 到 declare 变量使用
let,const, orvar变量 exists in 不同作用域 and isn't accessible 这里
最小示例
✗ 错误代码
console.log(userName);✓ 修复代码
const userName = "Alice";
console.log(userName);用户名 是从不 declared, 所以 JavaScript throws ReferenceError — declare 它使用 const 之前 using 它.
如何诊断
检查 spelling 的变量 name 针对它的 declaration
验证变量是 declared 使用
let,const, orvar之前 use检查作用域 — 是 declaration 可见从 哪里错误 occurs?
如何修复
Declare 变量使用
constorlet之前 using 它Fix typo 到 match declared name
Move declaration 到作用域 accessible 从 usage site
如何预防
总是 declare 变量使用
constorlet— 从不 use bare assignments启用 ESLint 使用
no-undef规则到 catch undeclared 变量
相关资源
相关课程
- 变量
学习如何 JavaScript 变量工作
相关练习
- Let 对比 Const 测验
测试你的理解的 变量 declaration 使用 const.
- Declare JavaScript 常量
练习 declaring 变量使用 const.