Is JavaScript's double equals (==) always symm

2019-02-04 00:11发布

There are many cases in which JavaScript's type-coercing equality operator is not transitive. For example, see "JavaScript equality transitivity is weird."

However, are there any cases in which == isn't symmetric? That is, where a == b is true and b == a is false?

3条回答
一纸荒年 Trace。
2楼-- · 2019-02-04 00:53

It's supposed to be symmetric. However, there is an asymmetric case in some versions of IE:

window == document; // true
document == window; // false
查看更多
混吃等死
3楼-- · 2019-02-04 01:04

In Javascript, == is always symmetric.

The spec says:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.
查看更多
小情绪 Triste *
4楼-- · 2019-02-04 01:05

The answer to your actual question (is the operator symmetric) is yes. The ECMA-262 spec explicitly states:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.
查看更多
登录 后发表回答