== 和 === 对象相同吗?
Are == and === the same for objects?
我知道 ==
和 ===
应用于原始值时的区别。但是对于对象来说,它们似乎都是简单的身份比较。
var a = {}
var b = a
var c = {}
a == b // true
a === b // true
a == c // false
a === c // false
在任何情况下,比较两个对象会为每个运算符提供不同的结果,还是它们在功能上是等价的?
看起来像
我知道 "check for object equality" 在 javascript 中的唯一方法是深入检查每个可能的键(但即便如此,它也只是鸭子类型检查)
嗯... ===
是 "compare identity and type"。您已确定要比较两个对象(因此 "type" 相同),剩下 "compare identity",与 ==
.
相同
同样,如果你比较两个number
,因为你已经知道它们是同一类型(number
),所以===
与==
相同。这里的对象与基元没有什么特别或不同的地方。只是对象的唯一类型是 object
.
是的,用 ==
比较两个对象与用 ===
比较它们是一样的。正如用 ==
比较两个字符串与 ===
是一样的。如果值的类型相同,则两种比较方法都会给出相同的结果。 As the specification states:
7.2.14 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed
as follows:
- If Type(x) is the same as Type(y), then
- Return the result of
performing Strict Equality Comparison x === y.
===
中的额外 = 确保两边的类型相同。 a
和 c
都是对象,类型相同。所以 ==
或 ===
在这里无关紧要。
我知道 ==
和 ===
应用于原始值时的区别。但是对于对象来说,它们似乎都是简单的身份比较。
var a = {}
var b = a
var c = {}
a == b // true
a === b // true
a == c // false
a === c // false
在任何情况下,比较两个对象会为每个运算符提供不同的结果,还是它们在功能上是等价的?
看起来像
我知道 "check for object equality" 在 javascript 中的唯一方法是深入检查每个可能的键(但即便如此,它也只是鸭子类型检查)
嗯... ===
是 "compare identity and type"。您已确定要比较两个对象(因此 "type" 相同),剩下 "compare identity",与 ==
.
同样,如果你比较两个number
,因为你已经知道它们是同一类型(number
),所以===
与==
相同。这里的对象与基元没有什么特别或不同的地方。只是对象的唯一类型是 object
.
是的,用 ==
比较两个对象与用 ===
比较它们是一样的。正如用 ==
比较两个字符串与 ===
是一样的。如果值的类型相同,则两种比较方法都会给出相同的结果。 As the specification states:
7.2.14 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is the same as Type(y), then
- Return the result of performing Strict Equality Comparison x === y.
===
中的额外 = 确保两边的类型相同。 a
和 c
都是对象,类型相同。所以 ==
或 ===
在这里无关紧要。