30秒学会 JavaScript 片段 · 2022年7月20日

30秒学会 JavaScript 片段 – Check object equality

Performs a deep comparison between two values to determine if they are equivalent.

  • Check if the two values are identical.
  • Check if both values are Date objects with the same time, using Date.prototype.getTime().
  • Check if both values are non-object values with an equivalent value (strict comparison).
  • Check if only one value is null or undefined or if their prototypes differ.
  • If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys.
  • Use Array.prototype.every() to check if every key in a exists in b and if they are equivalent by calling equals() recursively.

代码实现

const equals = (a, b) => {
  if (a === b) return true;

  if (a instanceof Date && b instanceof Date)
    return a.getTime() === b.getTime();

  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object'))
    return a === b;

  if (a.prototype !== b.prototype) return false;

  const keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;

  return keys.every(k => equals(a[k], b[k]));
};

equals(
  { a: [2, { e: 3 }], b: [4], c: 'foo' },
  { a: [2, { e: 3 }], b: [4], c: 'foo' }
); // true
equals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }); // true

翻译自:https://www.30secondsofcode.org/js/s/deep-equality-comparison