了解undefined、null、NaN的区别

1.常规的解释,null是个对象,表示空值,undefined也是个对象,表示没有定义

 

2.详细分析

null

书上的解释(Javascript权威指南)Javascript的关键词null是一种特殊的值,它表示“无值”。null常常被看作对象类型的一个特殊值,即代表“无对象”的值。如果一个变量的值为null,那么你就会知道它的值不是有效的对象、数组、数字、字符串和布尔值。null对应类型object,布尔值false,数字0,字符串“null

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var test = null;
 
//类型,输出object
document.write( typeof (test));
document.write("<br/>");
 
//字符串,输出nulltest
document.write(test + 'test');
document.write("<br/>");
 
//数字,输出10
document.write(test + 10);
document.write("<br/>");
 
//布尔值,输出false
if (test) {
   document.write("true");
}
if (!test) {
   document.write("false");
}

什么情况下会返回null

document.getElementById(‘XXX’); 寻找一个不存在的元素,返回null

 

undefined

undefinedwindow对象的一个属性,且不是关键词。书上解释,当你使用了一个并未声明的变量时,或者使用了已经声明但还没有赋值的变量时,又或者使用了一个并不存在的对象属性时,返回的就是这个值。undefined对应类型undefined,布尔型false,字符串undefined,数字计算结果一定是NaN

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var test;
 
//类型,输出undefined
document.write( typeof (test));
document.write("<br/>");
 
//字符串,输出undefinedtest
document.write(test + 'test');
document.write("<br/>");
 
//数字,输出NaN
document.write(test + 10);
document.write("<br/>");
 
//布尔值,输出false
if (test) {
   document.write("true");
}
if (!test) {
   document.write("false");
}

什么情况下会返回undefined,有人总结了如下几种场景

1.    直接访问没有修改的全局变量undefinedvar x = undefined x的值为undefined

2.    使用没有声明的变量,在IE下出错,提示”xxx”未定义;已经声明,没有赋值,类似var x; alert(x);      弹出undefined

3.    使用了一个不存在的对象的属性

 
1
2
3
4
5
var coffee = {
   x:'1',
   y:2
}
alert(coffee.z);

上面有提到过undefined不是javascript的关键词,所以可以定义一个名字为undefined的变量,如下

 
1
2
3
4
5
var undefined = 10;
 
document.write( typeof (undefined));
document.write("<br/>")
document.write(undefined * 10);

IE和搜狗浏览器下,返回结果    number             100

firefoxchrome下,返回结果  undefined         NaN

所以最好不要使用undefined的变量名

 

使用undefined的一个场景

在某个场景中经常要用到undefined,最好定义一个变量类似

var x = undefined,可以提高性能。这是因为javascript引擎在使用undefined的时候都是遍历window对象,寻找undefined属性,遍历属性过程中会造成大量的时间。

 

nullundefined的比较

null == undefined 返回true

null===undefined  返回false

 

对 undefined 的优化

当我们在程序中使用 undefined 时,实际使用的是 window 对象的 undefined 属性,由于 window 对象的属性很多,在每一次与 undefined交时,搜索 window 对象的 undefined 属性都会花费时间。在需要经常使用 undefined 的场景中,可以定义一个局部的 undefined 变量。

例如:var undefined;

 

最后引用淘宝玉伯对nullundefined的解释

值类型的“虚无”用undefined,引用类型的“虚无”,用null

原文地址:https://www.cnblogs.com/qiangspecial/p/3529048.html