Deeply compares two objects for equality

== and === compare

Two Object type objects, even if they have the same properties and the same value, are not considered equal when using == or === for comparison. This is because they are compared by reference (location in memory), unlike primitive types which are compared by value.

var obj1 = {
    
    
    name: "kite",
    sex : "male"
}
var obj2 = {
    
    
    name: "kite",
    sex : "male"
}
console.log(obj1 === obj2); // false

Recursive deep comparison

To check for "value equality" of an object we are basically iterating over each property of the object to compare if they are equal

/*
 * @param x {Object} 对象1
 * @param y {Object} 对象2
 * @return  {Boolean} true 为相等,false 为不等
 */
export function deepEqual(x, y) {
    
    
  // 指向同一内存时 直接返回true
  if (x === y) {
    
    
    return true;
  } 
  if ((typeof x === "object" && x !== null) && (typeof y === "object" && y !== null)) {
    
    
    if (Object.keys(x).length !== Object.keys(y).length) {
    
    
      // 键的数量不相等,直接返回false
      return false;
    }
    for (const prop in x) {
    
    
      if (y.hasOwnProperty(prop)) {
    
      
        if (!deepEqual(x[prop], y[prop])) return false;
      } else {
    
    
        return false;
      }
    }
    return true;
  }
  return false;
}

lodash ——isEqual

var object = {
    
     'a': 1 };
var other = {
    
     'a': 1 };
 
_.isEqual(object, other);
// => true
 
object === other;
// => false

Guess you like

Origin blog.csdn.net/qq_44376306/article/details/126287370