null和undefined

380 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第16天,点击查看活动详情

在js的语言类型那篇文章中介绍过null和undefined。null表示变量已经定义了并且存在,但是没有类型或值。也就是说它指向的是个空指针。undefined表示这个变量未被初始化或者没有定义。这篇文章我们从应用层面去介绍它们的区别。

数据类型

我们知道对于基本类型的变量,如果要判断类型的话,可以直接使用typeOf。下面我们就来看一下他们的区别。

console.log(typeof null) //object

console.log(typeof undefined) //undefined

在 javascript 的最初版本中,使用的 32位系统,js为了性能优化,使用低位来存储变量的类型信息。

数据类型机器码标识
对象000
整数1
浮点数010
字符串100
布尔110
undefined全为1
null全为0

在判断数据类型时,是根据机器码低位标识来判断的,而null的机器码标识为全0,而对象的机器码低位标识为000。所以typeof null的结果被误判为Object。

相等比较

== 是相似比较,不会校验类型,===是会校验类型的,因此就有了下面这种打印的结果

console.log(null == null);   // true
console.log(undefined == undefined);  // true
console.log(null === null);   // true
console.log(undefined === undefined);  // true
console.log(null == undefined);   // true
console.log(null === undefined);   // false

Number()和运算

Number()在类型转换的时候,以及在使用运算符都会进行类型转换,null和undefined在进行类型转换的时候的是不一样。

console.log(Number(null));   // 0
console.log(Number(undefined));  // NaN
console.log(null + 2);  // 2
console.log(undefined + 2);   // NaN

Object.prototype.toString.call

Object.prototype.toString.call可以精准地获取数据类型,对于null和undefined都可以返回对应的Null和Undefined。

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

JSON

JSON.stringify 方法将某个对象转换成 JSON 字符串形式。对于undefined来说是不能被转化的。JSON 会将 undefined 对应的 key 删除,这是 JSON 自身的转换原则。

JSON.stringify({a: undefined})  // '{}'
JSON.stringify({b: null})  // '{b: null}'
JSON.stringify({a: undefined, b: null})  // '{b: null}'

null和undefined的典型用法

null
  • 作为函数的参数,来表示该函数的参数不是对象
  • 作为对象原型链的终点
 Object.getPrototypeOf(Object.prototype)  // null
undefined
  • 变量被声明了,但没有赋值时,就等于undefined。
  • 调用函数时,应该提供的参数没有提供,该参数等于undefined。
  • 对象没有赋值的属性,该属性的值为undefined。
  • 函数没有返回值时,默认返回undefined。

特别说明 在实际开发中我们一定要注意是否为null或undefined, 对于这两种情况需要做出判断,比如:

let a = undefined
let b = null
if (!a) {
    console.log('undefined is false');  // undefined is false
}
if (!b) {
    console.log('null is false');  // null is false
}

所以我们通常可以直接这样判断

if (!变量) {}