Undefined 和 Null 虽然是两种不同的基本数据类型,存在一些不同的特性,但在某些表现上却存在着相同之处,所以在这里主要讲解下 Undefined 和 Null 在 JavaScript 中的相同点与不同点。
相同点
- Undefined 和 Null 两种数据类型都只有一个字面值,分别是
undefined
和null
; - Undefined 类型和 Null 类型在转换为 Boolean 类型的值时,都会转换为
false
。所以若是通过非运算符(!
)获取结果为true
的变量时,无法判断其值为undefined
还是null
; - 在需要将两者转换成对象时,将会抛出
TypeError
异常,这也是平时最常见的引用异常;
let a;
let b = null;
console.log(a.name); // Uncaught TypeError: Cannot read property 'name' of undefined
console.log(b.name); // Uncaught TypeError: Cannot read property 'name' of null
上述代码表示在通过某个变量引用name
属性时,若该变量值实际为undefined
或者null
,就会抛出异常。
- Undefined 类型派生自 Null 类型,所以在非严格相等的情况下,两者是相等的,如下述代码所示:
null == undefined //true
不同点
null
是 JavaScript 中的关键词,而undefined
是 JavaScript 中的一个全局变量,即挂载在 Window 上的一个变量,并不是关键词;- 在使用
TypeOf
运算符检测时,Undefined 类型的值会返回undefined
,而 Null 类型的值则会返回object
; - 在通过
cell
调用toString()
函数时,Undefined 类型的值会返回[Object Undefined]
,而 Null 类型的值则会返回object
; - 在需要进行字符串类型转换时,null 会转换为字符串的
null
,而 undefined 则会转换为字符串的undefined
; - 在 undefined 或 NaN 参与计算时,undefined 会被转换为
NaN
,无法参与计算,而 null 会转换为0
,可以参与计算。
建议
无论在任何情况下,都不建议将一个变量设置为undefined
。如果需要定义某个变量来保存将来要使用的对象,建议将其初始化为null
。这样的话不仅可以将null
作为空对象指针的惯例,还有助于区分null
和undefined
。