一. 使用场景
- 在非严格场景下, 两者值是相等的
let a = null;
let b = undefined;
console.log(a == b) // true
console.log(a === b) // false
- 在条件判断表达式中,两者作用也是相等的
if (null) {
console.log('null', null)
} else {
console.log('!null', !null) // 此项会输出 !null true
}
if (undefined) {
console.log('undefined', undefined)
} else {
console.log('!undefined', !undefined) // 此项会输出 !undefined true
}
- 对null和undefind进行数值类型强制类型转换
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
为何两者得到的结果不一样呢?很显然,两者是完全不同的两种类型
console.log(typeof null) // object
console.log(typeof undefined) // undefined
可以看到null 是Object类型,undefined 是Undefined类型,看到这里我不禁有了一个疑问,如果null是引用数据类型,那么我在MDN上看到的null则是基本数据类型,是MDN写错了?
所以使用typeof判断变量类型的方式并不准确。
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
所以null依然是基本数据类型Null, undefined也是基本数据类型Undefined
二. 那么JS为何会有两个令人困惑的类型呢?
首先我们需要先了解一个null值是什么?MDN上是这样描述的:In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. The meaning of a null reference varies among language implementations.
翻译过来就是: 在计算机科学中,一个null值代表一个指针的引用,通常来指一个不存在的或者无效的对象或者地址。空引用的含义因语言实现而异。
在1995年JavaScript诞生的时候,只设置了null值,并被设计为可以自动转为0。null表示为空对象的引用,由于JavaScript数据类型分为基本数据类型和引用数据类型,所以JavaScript的设计者Brendan Eich认为最好不要用null表示基本数据类型变量未初始化时的值,所以后来又定义了undefined来表示基本数据类型未初始化时的值。