Javascript:两个Object / Array之间的等式比较 [英] Javascript: Equality Comparison between two Object/ Array
问题描述
让我们猜两个具有相同属性的对象:
Let us guess two objects with same property:
var x = {a : 'some'},
y = {a: 'some'};
输出:
x == y;
和 x === y;
两者都给出错误
同样对于两个数组,
var p = [1, 2, 3],
q = [1,2,3];
p == q
和 p === q
两者都给 false
。
但是对于if我这样做:
But for if I do following:
var x = y = {a: 'some'};
var p = q = [1, 2, 3];
以上所有比较都给出 true
。
为什么Javascript会这样做?请解释。
Why Javascript do such thing? Explain Please.
推荐答案
以上所有比较都给出
true
。
对。你专门设置了 p
和 q
,所以它们引用了同一个对象。
Right. You've specifically set p
and q
so they refer to the same object.
使用对象引用, ==
(如果双方都是对象引用)和 ===
将检查引用是否指向同一对象。如果你有两个完全相同但又分开的对象,那么它们总是 false
。
With object references, both ==
(if both sides are object references) and ===
will check to see if the references are pointing to the same object. If you have two identical, but separate, objects, both will always be false
.
所以例如:
var a = {}; // a points to an object
var b = {}; // b points to a _different_ object
console.log(a === b); // "false"
console.log(a == b); // "false"
var c = {}; // c points to an object
var d = c; // d points to _the same_ object
console.log(c === d); // "true"
console.log(c == d); // "true"
对象的内容无关紧要,它是正在检查它们的身份。
The content of the objects is irrelevant, it's the identity of them that's being checked.
请注意,如果您使用 ==
并且只有一个side是对象引用(例如,另一方是数字,原始字符串, undefined
等)。在这种情况下,将要求对象引用自身转换(转换为字符串或数字,具体取决于其他内容),然后转换后的结果将用于比较。这可能导致令人惊讶的行为(例如,2== [[[[[2]]]]]
是 true
因为要求数组将自己变成一个字符串,它通过 join
[它将要求其元素将自身转换为字符串,依此类推],你在右边最后得到2
。所以我通常更喜欢 ===
(严格平等超过 ==
(松散平等)。
Note that this is not true if you use ==
and only one side is an object reference (e.g., the other side is a number, a primitive string, undefined
, etc.). In that case, the object reference will be asked to convert itself (to either a string or a number, depending on what the other thing is), and then the converted result will be used for the comparison. This can lead to surprising behavior (for instance, "2" == [[[[[2]]]]]
is true
because the array is asked to turn itself into a string, which it does via join
[which will ask its element to convert itself to a string, and so on], and you end up with "2"
on the right-hand side). So I typically prefer ===
("strict equality" over ==
("loose equality").
这篇关于Javascript:两个Object / Array之间的等式比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!