程序员首页投稿(暂停使用,暂停投稿)我说技术

null 和 undefined

2015-09-09  本文已影响1588人  d6e83ee69161
null And undefined

众所周知,JavaScript中的基本类型(基本类型指它们的值不是一个对象并且没有任何方法)为:String/Number/Bool/Null/Undefined/Symbol (ECMAScript 2015新增)

前几种是很容易弄明白的,但是Null/Undefined总是相互纠缠,让人弄不明白。之前一直没有在意Null 和 Undefined类型根本的差别,只是简单的了解一下,今天被面试官问到:请说一下null 和 undefined的区别。我张了张嘴,竟然没法准确地答出来。

回来翻了翻各种资料,包括MDN上的资料、ECMAScript规范、红宝书,发现这还真是一个世界性难题。

规范中的描述:


ECMAScript-262 3th Edition:

4.3.9 Undefined Value
The undefined value is a primitive value used when a variable has not been assigned a value.
// undefined是一个原始值,一个变量尚未被分配一个值时会使用到它

4.3.11 Null Value
The null value is a primitive value that represents the null, empty, or non-existent reference.
// null是一个原始值,被用来表示零、空或者不存在的引用

ECMAScript-262 5th Edition And 6th Edition(相较于3th版基本没有变动):

4.3.9
undefined value
primitive value used when a variable has not been assigned a value.
// 原始值,一个变量尚未被分配值时会被使用到
4.3.11
null value
primitive value that represents the intentional absence of any object value.
// 原始值,表示对任何对象值的有意的缺失

MDN文档中的描述:


typeof  null  // object (bug in ECMAScript, should be null)
typeof undefined  // undefined
null === undefined // false
null == undefined // true

JavaScript高级程序设计里的描述:

疑惑点:


5 + null   // 5
5 + undefined  //NaN

null在其它语言中经常被用来当作空指针使用。空指针是一个特殊的指针值。指针变量具有空指针值,表示它当时处于闲置状态,没有指向任何有意义的东西。空指针指向内存的0地址,但是0地址附近的空间是归操作系统所有,别的指向是不允许使用的。所以指针指向0地址是为了使指针指向一个已知的地方防止成为野指针。

这么考虑下来在JS当中参与数字运算的时候,把null值转换成0也不是没有道理,而undefined就没有这层含义了,所以不能参与和数字的运算,但是值得注意的是:

parseInt(null)  // NaN
parseInt(undefined)  // NaN
console.log(a);  // Uncaught ReferenceError: a is not defined 

上面提示很具有迷惑性,说a not defined,那就是undefined喽?NONONO!这里是指a未被声明,称之为undeclared更为准确。

var a;
console.log(a) // undefined

上面定义了a,但是未赋值,所以默认值为undefined
注意:请不要手动将一个变量设为undefined,这是没有意义的,如果不想要它,请把它delete.

typeof a (a是一个没有声明过的变量或是声明了没有赋值) 都会出现undefined;

参考资料:

阮一峰老师的文章(图片也是来自此文):
http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

Stack OverFlow上问题:http://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript

ECMAScript规范:http://www.ecmascript.org/

MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

上一篇 下一篇

猜你喜欢

热点阅读