Why are two objects with the same values not equal? [duplicate]

时光怂恿深爱的人放手 提交于 2020-01-17 14:44:09

问题


I run the following in console why is the output false. Not asking how to compare two objects but why these two objects are not same.

> a = {same:'same'}
Object {same: "same"}
> b = {same:'same'}
Object {same: "same"}
> a === b
false
> a == b
false

回答1:


Two objects are never the same even if they have the same content, as two different instances of Object is never equal.

When comparing two object, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys and values are not checked, so the content of the object doesn't matter, the operands both have to reference the same object to return true in a comparison.




回答2:


This is simply due to how == is defined per the The Abstract Equality Comparison Algorithm:

1. If Type(x) is the same as Type(y) [i.e. Type(x) == Type(y) == Object], then ..

1.f. Return true if x and y refer to the same object. Otherwise, return false.

None of the other rules/conversions apply because both operands are Objects.

Although there is no ECMAScript 5th edition "core" support for this task, several solutions are discussed in How to determine equality for two JavaScript objects?


This has naught to do with "references", which are an implementation detail not defined in ECMAScript, and can be entirely discussed per the above rules: two different Objects are never equal per == (and by extension ===) rules.




回答3:


You are comparing two objects which never be equal. If you compare a.same and b.same then they will be the same.



来源:https://stackoverflow.com/questions/22828341/why-are-two-objects-with-the-same-values-not-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!