本书未发布
undefined 和 null 的异同
相同点
两种数据类型都只有一个字面值, 即
undefined
和null
两种数据类型在转换成布尔类型的时候, 都会转换成
false
, 所以在通过 ! 来取反的时候, 没有办法判断到底是undefined
还是false
当将两者转换成对象的时候, 都会抛出一个
TypeError
的异常, 如下:let a; let b = null; console.log(a.name); // Cannot read property 'name' of undefined console.log(b.name); // Cannot read property 'name' of null
在非严格情况下, undefined 和 null 是相等的
true == undefined; // true
不同点:
- null 是JavaScript 中的关键字, 而 undefined 是一个全局变量, 就是挂载在 Window 对象中的一个变量, 不是关键字
- 在使用 typeof() 检测数据类型的时候, undefined 返回的是 undefined, null 返回的是 object
- 在通过 call 调用 toString() 函数时, undefined 类型的值会返回 [object Undefined], null 类型会返回 [object Null]
Object.prototype.toString().call(undefined); // [object Undefined] Object.prototype.toString().call(null); // [object Null]
- 在进行字符串类型转换的时候, null 会转换成字符串的 ‘null’, undefined 会转换成字符串的 ‘undefined’
- 在进行数值计算的时候, undefined 会转换成 NaN, 无法参与计算; null 会转换成 0, 可以参与计算
- 无论在什么情况下, 都没有必要将一个变量显示的设置成 undefined. 如果需要定义一个变量来存将来要使用的对象, 那么应该将其初始化为 null
推荐文章: