undefined 与 null

undefined 与 null 都是 JavaScript 的基本数据类型,在转换为 Boolean 类型时也都会转换为 false。它们有什么区别呢?

1.null 是一个表示「无」的对象,转为数值时为 0;undefined 是一个表示「无」的原始值,转为数值时为 NaN。

Number(null); // 0
null == 0; // false
Number(undefined); // NaN

typeof null; // "object"
typeof undefined; // "undefined"

2.undefined 是全局对象(window)的一个属性。

当我们将一个变量或值与 undefined 比较时,实际上是与 window 对象的 undefined 属性比较。这个比较过程中,JavaScript 会搜索 window 对象名叫 undefined 的属性,然后再比较两个操作数的引用指针是否相同。
由于 window 对象的属性值非常多,在每一次与 undefined 的比较中,搜索 window 对象的 undefined 属性都会花费时间。在需要频繁与 undefined 进行比较的函数中,这可能会是一个性能问题点。因此,在这种情况下,我们可以自行定义一个局部的 undefined 变量,来加快对 undefined 的比较速度。

function (){
    var undefined;
    ...
    if (x === undefined){
    ...
    }
}

3.如何检测 undefined 与 null

var a = undefined, b = null;

a === undefined; // true
typeof a === "undefined"; // true
b === null; // true

Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"

4.返回 undefined 与 null 的不同情况

undefined:
(1)访问声明时未提供初始值的变量
(2)访问不存在的数组项或对象属性
(3)省略了函数返回语句的函数,返回 undefined
(4)函数中本应提供但没有提供的参数,值为 undefined
(5)全局变量的属性

null:
(1)不存在的 DOM
(2)垃圾回收

总而言之,undefined 是一个意料之外的空值,null 是一个意料之中的空值。

参考:
http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html
http://blog.csdn.net/leadzen/article/details/3899392
http://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and
https://leohxj.gitbooks.io/front-end-database/content/javascript-basic/difference-between-undefined-and-null.html

你可能感兴趣的:(undefined 与 null)