JavaScript判断对象是否相等

2019-02-15  本文已影响0人  January丶缘

在Javascript中相等运算包括"==","===",两者不同之处,不必细说。本文主要跟大家探讨如何判断两个对象是否相等。有人可能认为两个对象有相同的属性以及对应的属相有相同的值,那么这两个对象就相等。事实是这样吗?我们验证一下:

var obj0 = {
    name: "zhangsan",
    age: 18
}
var obj1 = {
    name: "zhangsan",
    age: 18
}
 
//Outputs: false
console.log(obj0 == obj1);
 
//Outputs: false
console.log(obj0 === obj1);

通过例子我们很明显发现,无论是“==”还是“===”都返回false。原因是:基本类型string,number通过值来比较,而对象(Date,Array,Function)及普通对象通过指针指向的内存中的地址来做比较。以上例子我们做个修改就能看出端倪:

var obj0 = {
    name: "zhangsan",
    age: 18
}
var obj1 = {
    name: "zhangsan",
    age: 18
}
var obj2 = obj0;

//Outputs: true
console.log(obj0 == obj2);

//Outputs: true
console.log(obj0 === obj2);

//Outputs: false
console.log(obj1 == obj2);
 
//Outputs: false
console.log(obj1 === obj2);

修改之后返回true。原因是obj0和ob3的指针指向了内存中的同一个地址;这和面向对象的语言(Java/C)中值传递和引用传递的概念相似。如果你想判断两个对象是否相等,首先要明确你是想判断两个对象的属性是否相同,还是属性对应的值是否相同,还是其他。如果你判断两个对象的值是否相等,可以这样:

function isObjectValueEqual(a, b) {
    // 获取对象的属性集合(数组)
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // 属性个数(长度)不同,对象肯定不同
    if (aProps.length != bProps.length) {
        return false;
    }
 
    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];
        if (a[propName] !== b[propName]) {
            return false;
        }
    }
    return true;
}

var obj0 = {
    name: "zhangsan",
    age: 18
}
var obj1 = {
    name: "zhangsan",
    age: 18
}
//Outputs: true
console.log(isObjectValueEqual(obj0, obj1));

检查对象的“值相等”我们基本上是要遍历的对象的每个属性,看看它们是否相等。虽然这个简单的实现适用于我们的例子中,但是却不能通用。我们知道JavaScript中的对象不仅仅是例子中的那种简单对象,还有(Array,Date,Function)等等。这样一来我们的方法就会出现判断不出的情况:

1、对象某个属性值为其他对象(Array,Date,String,Function)等
2、对象某个属性值为underfined,另一个对象没有这个属性值
3、对象某个属性值为NaN(未深入研究)

最后经过度娘找到一个检查对象的“值相等”的一个强大的方法,它依靠完善的测试库,涵盖了各种边界情况。Underscore和Lo-Dash有一个名为_.isEqual()方法,用来比较好的处理深度对象的比较。

// Outputs: true
console.log(_.isEqual(obj0, obj1));

// Underscore中isEqual的部分源码
var eq = function(a, b, aStack, bStack) {
  // Identical objects are equal. `0 === -0`, but they aren't identical.
  // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
  if (a === b) return a !== 0 || 1 / a === 1 / b;
  // A strict comparison is necessary because `null == undefined`.
  if (a == null || b == null) return a === b;
  // Unwrap any wrapped objects.
  if (a instanceof _) a = a._wrapped;
  if (b instanceof _) b = b._wrapped;
  // Compare `[[Class]]` names.
  var className = toString.call(a);
  if (className !== toString.call(b)) return false;
  switch (className) {
    // Strings, numbers, regular expressions, dates, and booleans are compared by value.
    case '[object RegExp]':
    // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
    case '[object String]':
      // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
      // equivalent to `new String("5")`.
      return '' + a === '' + b;
    case '[object Number]':
      // `NaN`s are equivalent, but non-reflexive.
      // Object(NaN) is equivalent to NaN
      if (+a !== +a) return +b !== +b;
      // An `egal` comparison is performed for other numeric values.
      return +a === 0 ? 1 / +a === 1 / b : +a === +b;
    case '[object Date]':
    case '[object Boolean]':
      // Coerce dates and booleans to numeric primitive values. Dates are compared by their
      // millisecond representations. Note that invalid dates with millisecond representations
      // of `NaN` are not equivalent.
      return +a === +b;
  }
  if (typeof a != 'object' || typeof b != 'object') return false;
  // Assume equality for cyclic structures. The algorithm for detecting cyclic
  // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  var length = aStack.length;
  while (length--) {
    // Linear search. Performance is inversely proportional to the number of
    // unique nested structures.
    if (aStack[length] === a) return bStack[length] === b;
  }
  // Objects with different constructors are not equivalent, but `Object`s
  // from different frames are.
  var aCtor = a.constructor, bCtor = b.constructor;
  if (
    aCtor !== bCtor &&
    // Handle Object.create(x) cases
    'constructor' in a && 'constructor' in b &&
    !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
      _.isFunction(bCtor) && bCtor instanceof bCtor)
  ) {
    return false;
  }
  // Add the first object to the stack of traversed objects.
  aStack.push(a);
  bStack.push(b);
  var size, result;
  // Recursively compare objects and arrays.
  if (className === '[object Array]') {
    // Compare array lengths to determine if a deep comparison is necessary.
    size = a.length;
    result = size === b.length;
    if (result) {
      // Deep compare the contents, ignoring non-numeric properties.
      while (size--) {
        if (!(result = eq(a[size], b[size], aStack, bStack))) break;
      }
    }
  } else {
    // Deep compare objects.
    var keys = _.keys(a), key;
    size = keys.length;
    // Ensure that both objects contain the same number of properties before comparing deep equality.
    result = _.keys(b).length === size;
    if (result) {
      while (size--) {
        // Deep compare each member
        key = keys[size];
        if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
      }
    }
  }
  // Remove the first object from the stack of traversed objects.
  aStack.pop();
  bStack.pop();
  return result;
};
 
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
  return eq(a, b, [], []);
};

上一篇下一篇

猜你喜欢

热点阅读