首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

undefined

全局属性undefined表示原始值undefined它是一个JavaScript的原始数据类型

| Property attributes of undefined |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | no |

语法

代码语言:javascript
复制
undefined

描述

undefined是全局对象的一个属性。也就是说,它是全局作用域的一个变量。undefined的最初值就是原始数据类型undefined

在现代浏览器(JavaScript 1.8.5/Firefox 4+),自ECMAscript5标准以来undefined是一个不能被配置(non-configurable),不能被重写(non-writable)的属性。即便事实并非如此,也要避免去重写它。

一个没有被赋值的变量的类型是undefined。如果方法或者是语句中操作的变量没有被赋值,则会返回undefined(对于这句话持疑惑态度,请查看英文原文来理解)。一个函数如果没有返回值,就会返回一个undefined值。

但是它有可能在非全局作用域中被当作标识符(变量名)来使用(因为undefined不是一个保留字)),这样做是一个非常坏的主意,因为这样会使你的代码难以去维护和排错。

代码语言:javascript
复制
//DON'T DO THIS 别这么做!

// logs "foo string"
(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();

// logs "foo string"
(function(undefined) { console.log(undefined, typeof undefined); })('foo');

示例

严格相等和undefined

你可以使用undefined和严格相等或不相等操作符来决定一个变量是否拥有值。在下面的代码中,变量x是未定义的,if 语句的求值结果将是true

代码语言:javascript
复制
var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}

注意:这里是必须使用严格相等操作符(===)而不是标准相等操作符(==),因为 x == undefined 会检查x是不是null,但是严格相等不会检查。null不等同于undefined。移步比较操作符查看详情。

Typeof 操作符和undefined

或者,可以使用typeof

代码语言:javascript
复制
var x;
if (typeof x === 'undefined') {
   // these statements execute
}

使用typeof的原因是它不会在一个变量没有被声明的时候抛出一个错误。

代码语言:javascript
复制
// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
   // these statements execute
}

if (x === undefined) { // throws a ReferenceError

}

但是,技术方面看来这样的使用方法应该被避免。JavaScript是一个静态作用域语言,所以,一个变量是否被声明可以通过看它是否在一个封闭的上下文中被声明。唯一的例外是全局作用域,但是全局作用域是被绑定在全局对象上的,所以要检查一个变量是否在全局上下文中存在可以通过检查全局对象上是否存在这个属性(比如使用in操作符)。

Void操作符和undefined

void操作符是第三种可以替代的方法。

代码语言:javascript
复制
var x;
if (x === void 0) {
   // these statements execute
}

// y has not been declared before
if (y === void 0) {
   // throws a ReferenceError (in contrast to `typeof`)
}

规范

Specification

Status

Comment

ECMAScript 1st Edition (ECMA-262)The definition of 'undefined' in that specification.

Standard

Initial definition. Implemented in JavaScript 1.3.

ECMAScript 5.1 (ECMA-262)The definition of 'undefined' in that specification.

Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'undefined' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'undefined' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券