参考错误:"x" 未定义

当某处引用了不存在的变量时,就会发生 JavaScript 异常 "变量未定义"。

¥The JavaScript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.

信息

¥Message

ReferenceError: "x" is not defined (V8-based & Firefox)
ReferenceError: Can't find variable: x (Safari)

错误类型

¥Error type

ReferenceError

什么地方出了错?

¥What went wrong?

某处引用了一个不存在的变量。该变量需要声明,或者你需要确保它在你当前的脚本或 scope.txt 中可用。

¥There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.

注意:加载库(例如 jQuery)时,请确保在访问库变量(例如 "$"。将加载库的 <script> 元素放在使用它的代码之前。

¥Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as "$". Put the <script> element that loads the library before your code that uses it.

示例

¥Examples

变量未声明

¥Variable not declared

js
foo.substring(1); // ReferenceError: foo is not defined

"foo" 变量未在任何地方定义。它需要是某个字符串,这样 String.prototype.substring() 方法才能起作用。

¥The "foo" variable isn't defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.

js
const foo = "bar";
foo.substring(1); // "ar"

范围错误

¥Wrong scope

变量需要在当前执行上下文中可用。无法从函数外部的任何地方访问在 function 内定义的变量,因为该变量仅在函数范围内定义

¥A variable needs to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function

js
function numbers() {
  const num1 = 2;
  const num2 = 3;
  return num1 + num2;
}

console.log(num1); // ReferenceError num1 is not defined.

但是,函数可以访问其定义范围内定义的所有变量和函数。换句话说,在全局作用域中定义的函数可以访问在全局作用域中定义的所有变量。

¥However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.

js
const num1 = 2;
const num2 = 3;

function numbers() {
  return num1 + num2;
}

console.log(numbers()); // 5

也可以看看