
英文 | https://javascript.plainenglish.io/6-secrets-about-null-and-undefined-that-you-should-know-bf759ab59bce
尽管我已经工作了很多年,但我对“null”和“undefined”还是有点模糊不清,我感到很惭愧。如果你也和我一样有关它们的困惑,请你认真看完这篇文章,它会告诉你一切。
每个人都知道,它们都是些基础知识。
上面这张图是一张非常有趣的图,或许它表达了 null 和 undefined 的本质区别。
null 和 undefined 都代表“null”,那么它们之间的主要区别是什么?
- undefined 表示该变量尚未定义。
- null 表示该变量已定义,但它不指向内存中的任何对象。
这是 null 和 undefined 最基本的区别,你必须非常清楚。
1. 为什么“typeof null”返回“object”?
null 和 {} 不一样,它不是对象类型的数据,但是为什么 typeof null 返回的是对象呢?
typeof null // 'object'
typeof undefined // 'undefined'
事实上,它是 JavaScript 从设计之初就存在的一个 bug,但直到现在都无法修复。
在 JavaScript 的初始版本中,所有值都以 32 位存储。前 3 位表示数据类型的令牌,其余位是值。
对于所有对象,对象的前 3 位标记为 000 作为类型标记位。在早期版本的 JavaScript 中,null 被认为是对应于 C 中的空指针的特殊值。但是,JavaScript 不像 C 中那样具有指针,因此 null 表示什么都没有或 void,并且由全 0 表示 (32)。
因此,每当 JavaScript 读取 null 时,前 3 位将其视为对象类型,这就是 typeof null 返回“object”的原因。
2. 为什么 == 和 === 给出不同的结果?
你知道为什么这段代码会给出完全不同的结果吗?
null == undefined // true
null === undefined // false
!!null === !!undefined // true
ECMA 在第 11.9.3 章清楚地告诉我们,
- 如果 x 为 null 且 y 未定义,则返回 true。
- 如果 x 未定义且 y 为空,则返回 true。
3. 为什么 null + 1 和 undefined + 1 返回的结果不同?
undefined + 1 // NaN
null + 1 // 1
Number(undefined) // NaN
Number(null) // 0
这涉及到 JavaScript 中的隐式类型转换,它尝试在执行加法运算之前将表达式中的变量转换为数字类型。例如,‘1’ + 1 将产生 11。
当 null 转换为数字时,它被转换为 0。
当 undefined 转为数字时,转为 NaN
4、为什么Object.prototype.toString.call(null)会输出‘[object Null]’?
toString() 是 Object 的原型方法。当我们调用这个方法时,它默认返回当前对象的[[Class]]。这是 [object Xxx] 形式的内部属性,其中 Xxx 是对象的类型。
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
5、为什么undefined可以被覆盖?
虽然,我们不太可能写出这样的代码,但它确实符合所有规范。
const changeUndefined = (name) => {
const undefined = 'fatfish'
return name === undefined
}
changeUndefined() // false
changeUndefined(undefined) // false
changeUndefined('fatfish') // ture
let undefined = 'fatfish' // Uncaught SyntaxError: Identifier 'undefined' has already been declared
JavaScript 在全局环境中创建了一个只读的 undefined 但并没有完全禁用本地 undefined 变量的定义。
所以,你仍然可以在函数中将变量声明为undefined,但这是个魔鬼,请停止这样做。
6. 为什么 JSON.stringify 会删除未定义值的内容?
JSON.stringify({ name: undefined }) // '{}'
JSON.stringify({ name: null }) // '{"name":null}'
JSON.stringify({ name: undefined, age: null}) // '{"age":null}'
其实,这篇文章也没有很好的解读方式。JSON.stringify 去掉了 undefined 对应的 key,这是 JSON 自己的转换原理。
如果你不熟悉 `JSON.stringify` 的转换规则而吃了大亏,你可以点击我之前分享的一篇文章《我的朋友因为 JSON.stringify 差点丢了奖金》去学习了解一下它的全部细节。
总结
以上就是我今天跟你分享的全部内容,如果你觉得有用的话,请记得点赞我,关注我,并将它分享给你身边的朋友,也许能够帮助到他。
最后,感谢你的阅读,祝编程愉快!