Why are two identical objects not equal to each other?

前端 未结 9 868
广开言路
广开言路 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: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.

提交回复
热议问题