分享 6 个你可能还不知道的关于 “null” 和 “undefined” 的秘密

09c6d4f1394b423af5446ba561e02cdf.jpeg

英文 | https://javascript.plainenglish.io/6-secrets-about-null-and-undefined-that-you-should-know-bf759ab59bce

尽管我已经工作了很多年,但我对“null”和“undefined”还是有点模糊不清,我感到很惭愧。如果你也和我一样有关它们的困惑,请你认真看完这篇文章,它会告诉你一切。

每个人都知道,它们都是些基础知识。

b055f63ffd4b6cdc3d2290ea877137f6.png

上面这张图是一张非常有趣的图,或许它表达了 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 自己的转换原理。

总结

以上就是我今天跟你分享的全部内容,如果你觉得有用的话,请记得点赞我,关注我,并将它分享给你身边的朋友,也许能够帮助到他。

最后,感谢你的阅读,祝编程愉快!

学习更多技能

请点击下方公众号

28e135b27779c369292dc231698afc07.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值