Why are two objects with the same values not equal

2019-09-20 10:50发布

This question already has an answer here:

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

3条回答
祖国的老花朵
2楼-- · 2019-09-20 10:54

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

查看更多
混吃等死
3楼-- · 2019-09-20 11:04

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.

查看更多
Deceive 欺骗
4楼-- · 2019-09-20 11:12

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.

查看更多
登录 后发表回答