js实现深度比较
function isEqual(x, y) { // 如果全等则直接返回 true if (x === y) { return true; } else if ( typeof x === "object" && x !== null && typeof y === "object" && y !== null ) { let xKeys = Object.keys(x); let yKeys = Object.keys(y); // 如果key的数量不一致,直接返回 false; if (xKeys.length !== yKeys.length) { return false; } for (const key of xKeys) { if (x[key] === y[key]) { return true; } else { return false; } } } else { return false; } } console.log(isEqual([1, 2, 3], [1, 2, 3])); // true console.log(isEqual([1, 2, 3], [1, 2, 3, 5])); // false console.log(isEqual(null, undefined)); // false console.log(isEqual(null, true)); // false console.log(isEqual(null, false)); // false console.log(isEqual(undefined, 0)); // false console.log(isEqual(null, null)); // true console.log(isEqual(NaN, NaN)); // false console.log(isEqual(false, 0)); // false console.log(isEqual({ a: 1 }, { a: 1 })); // true console.log(isEqual({ a: 1 }, { a: 1, b: 2 })); // false
参考:https://github.com/shfshanyue/Daily-Question/issues/614#issuecomment-886135655