Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 中的相等性判断 #4

Open
SuperTapir opened this issue Apr 5, 2020 · 0 comments
Open

JavaScript 中的相等性判断 #4

SuperTapir opened this issue Apr 5, 2020 · 0 comments

Comments

@SuperTapir
Copy link
Owner

SuperTapir commented Apr 5, 2020

这个其实是一个很容易让人忽略的问题,我们知道一些在 JavaScript 中判断相等性的方法,但是对于一些特别的值,他们之间有一些微妙的差别。

另外,在 JavaScript 的内部实现里,到底是如何判断相等的,这是一件很有趣的事情。

JavaScript 中的值的比较

  • === 严格相等
  • == 宽松相等
  • Object.is

这里 宽松相等的转型太多太杂,就不做对比了,主要比较 ===Object.is

x y === Object.is
null null
+0 -0
NaN NaN

在这里对比了一些比较微妙的值,其实对于 ===Object.is 就只有这两个不同

  • Object.is 的 NaN 和 NaN 相等
  • Object.is 的 +0 和 -0 不等

JavaScript 中的相等算法

  • Strict equality using ===
  • Loose equality using ==
  • Same-value equality using Object.is
  • Same-value-zero equality
    • Same-value equality 区别在于,认为 +0 和 -0 相等

这些算法用在哪里?

  • Strict equality using ===
    • Array.prototype.indexOf
    • Array.prototype.lastIndexOf
    • switch 语句 case 匹配
  • Loose equality using ==
  • Same-value-zero equality
    • 用于 %TypedArray%ArrayBuffer 构造函数
    • MapSet 操作
    • String.prototype.includes
  • Same-value equality
    • Object.defineProperty 在试图修改不可变属性时,如果这个属性确实被修改了则会抛出异常,反之什么都不会发生。这里的相等判断。
    • 其他所有地方

实际应用

我认为,一般来说 === 在大多数场合中,都够用了。

只有在一些特殊情况下,我们需要判断 +0 和 -0 时,才需要使用手动使用 Object.is

另外,比较有趣的是 MapSet 操作使用 Same-value-zero equality

参考资料

JavaScript 中的相等性判断

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant