Why are two identical objects not equal to each other?

前端 未结 9 662
广开言路
广开言路 2020-11-22 05:43

Seems like the following code should return a true, but it returns false.

var a = {};
var b = {};

console.log(a==b); //returns false
console.log(a===b); //         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:59

    How does this make sense?

    Imagine these two objects:

    var a = { someVar: 5 }
    var b = { another: 'hi' }
    

    Now if you did a === b, you would intuitively think it should be false (which is correct). But do you think it is false because the objects contain different keys, or because they are different objects? Next imagine removing the keys from each object:

    delete a.someVar
    delete b.another
    

    Both are now empty objects, but the equality check will still be exactly the same, because you are still comparing whether or not a and b are the same object (not whether they contain the same keys and values).

提交回复
热议问题