Why are two identical objects not equal to each other?

前端 未结 9 659
广开言路
广开言路 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条回答
  • 2020-11-22 06:04

    This is a workaround: Object.toJSON(obj1) == Object.toJSON(obj2)

    By converting to string, comprasion will basically be in strings

    0 讨论(0)
  • 2020-11-22 06:06
    In Javascript each object is unique hence `{} == {}` or `{} === {}` returns false. In other words Javascript compares objects by identity, not by value.
    
     1. Double equal to `( == )` Ex: `'1' == 1` returns true because type is excluded 
         
     2. Triple equal to `( === )` Ex: `'1' === 1` returns false compares strictly, checks for type even
    
    0 讨论(0)
  • 2020-11-22 06:16

    Here is a quick explanation of why {} === {} returns false in JavaScript:


    From MDN Web Docs - Working with objects: Comparing objects.

    In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

    // Two variables, two distinct objects with the same properties
    var fruit = {name: 'apple'};
    var fruitbear = {name: 'apple'};
    
    fruit == fruitbear; // return false
    fruit === fruitbear; // return false
    
    // Two variables, a single object
    var fruit = {name: 'apple'};
    var fruitbear = fruit;  // Assign fruit object reference to fruitbear
    
    // Here fruit and fruitbear are pointing to same object
    fruit == fruitbear; // return true
    fruit === fruitbear; // return true
    
    fruit.name = 'grape';
    console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }
    

    For more information about comparison operators, see Comparison operators.

    0 讨论(0)
提交回复
热议问题