方式一:手动比较
代码示例
jsfunction isObjectValueEqual(a, b) { // 获取对象 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; }使用示例
jsvar obj1 = { name: "Benjamin", sex: "male" }; var obj2 = { name: "Benjamin", sex: "male" }; var obj3 = { name: "John", sex: "male" }; console.log(isObjectValueEqual(obj1, obj2)); // true console.log(isObjectValueEqual(obj1, obj3)); // false
方式二:浅层比较
定义:浅层比较是指只比较对象的第一层属性值,而不深入比较嵌套的对象
代码示例
jsfunction shallowEqual(object1, object2) { const keys1 = Object.keys(object1); const keys2 = Object.keys(object2); if (keys1.length !== keys2.length) { return false; } for (let index = 0; index < keys1.length; index++) { const val1 = object1[keys1[index]]; const val2 = object2[keys2[index]]; if (val1 !== val2) { return false; } } return true; }使用示例
jsconst hero1 = { name: 'Batman', realName: 'Bruce Wayne' }; const hero2 = { name: 'Batman', realName: 'Bruce Wayne' }; const hero3 = { name: 'Joker' }; console.log(shallowEqual(hero1, hero2)); // true console.log(shallowEqual(hero1, hero3)); // false
方式三:深层比较
定义:深层比较不仅比较对象的第一层属性值,还会递归比较嵌套的对象,使用递归函数实现
代码示例
jsfunction deepEqual(object1, object2) { const keys1 = Object.keys(object1); const keys2 = Object.keys(object2); if (keys1.length !== keys2.length) { return false; } for (let index = 0; index < keys1.length; index++) { const val1 = object1[keys1[index]]; const val2 = object2[keys2[index]]; const areObjects = isObject(val1) && isObject(val2); if (areObjects && !deepEqual(val1, val2) || !areObjects && val1 !== val2) { return false; } } return true; } function isObject(object) { return object != null && typeof object === 'object'; }使用示例
jsconst hero1 = { name: 'Batman', address: { city: 'Gotham' } }; const hero2 = { name: 'Batman', address: { city: 'Gotham' } }; console.log(deepEqual(hero1, hero2)); // true