undefined
试一试
function test(t) {
if (t === undefined) {
return "Undefined value!";
}
return t;
}
let x;
console.log(test(x));
// Expected output: "Undefined value!"
值
原始值 undefined。
undefined 的属性特性 | |
|---|---|
| 可写 | 否 |
| 可枚举 | 否 |
| 可配置 | 否 |
描述
undefined 是全局对象的一个属性。也就是说,它是一个全局作用域中的变量。
在所有非传统浏览器中,undefined 是一个不可配置、不可写的属性。即使情况并非如此,也应避免覆盖它。
尚未赋值的变量的类型是 undefined。如果被评估的变量没有赋值,方法或语句也会返回 undefined。如果函数没有返回值,它也会返回 undefined。
示例
严格相等与 undefined
你可以使用 undefined 以及严格相等和不等运算符来判断变量是否有值。在下面的代码中,变量 x 未初始化,if 语句评估为 true。
js
let x;
if (x === undefined) {
// these statements execute
} else {
// these statements do not execute
}
注意:此处必须使用严格相等运算符(而不是标准相等运算符),因为 x == undefined 还会检查 x 是否为 null,而严格相等不会。这是因为 null 不等同于 undefined。
有关详细信息,请参阅相等比较和相同性。
typeof 运算符与 undefined
或者,可以使用 typeof
js
let x;
if (typeof x === "undefined") {
// these statements execute
}
使用 typeof 的一个原因是,如果变量未声明,它不会抛出错误。
js
// x has not been declared before
// evaluates to true without errors
if (typeof x === "undefined") {
// these statements execute
}
// Throws a ReferenceError
if (x === undefined) {
}
然而,还有另一种选择。JavaScript 是一种静态作用域语言,因此可以通过查看变量是否在封闭上下文中声明来判断它是否已声明。
全局作用域绑定到全局对象,因此可以通过检查全局对象上的属性是否存在来检查全局上下文中的变量是否存在,例如使用 in 运算符。
js
if ("x" in window) {
// These statements execute only if x is defined globally
}
void 运算符与 undefined
void 运算符是第三种选择。
js
let x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws Uncaught ReferenceError: y is not defined
}
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-undefined |
浏览器兼容性
加载中…