Why are two identical objects not equal to each other?

前端 未结 9 856
广开言路
广开言路 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 05:55

    As from The Definitive Guide to Javascript.

    Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order.

    var o = {x:1}, p = {x:1};  // Two objects with the same properties
    o === p                    // => false: distinct objects are never equal 
    var a = [], b = [];        // Two distinct, empty arrays 
    a === b                    // => false: distinct arrays are never equal 

    Objects are sometimes called reference types to distinguish them from JavaScript’s primitive types. Using this terminology, object values are references, and we say that objects are compared by reference: two object values are the same if and only if they refer to the same underlying object.

    var a = {};   // The variable a refers to an empty object. 
    var b = a;    // Now b refers to the same object. 
    b.property = 1;     // Mutate the object referred to by variable b. 
    a.property          // => 1: the change is also visible through variable a. 
    a === b       // => true: a and b refer to the same object, so they are equal. 

    If we want to compare two distinct objects we must compare their properties.

提交回复
热议问题