非常教程

JavaScript参考手册

全球对象 | Global Objects

undefined

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

| Property attributes of undefined |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | no |

语法

undefined

描述

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

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

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

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

//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

var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}

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

Typeof 操作符和undefined

或者,可以使用typeof

var x;
if (typeof x === 'undefined') {
   // these statements execute
}

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

// 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操作符是第三种可以替代的方法。

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)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络