js实现compare
JavaScript 实现对象/值比较
在 JavaScript 中比较对象或值时,需要根据数据类型和需求选择合适的方法。以下是几种常见的比较实现方式:
基本值比较
使用严格相等运算符 === 可以比较基本类型的值(number, string, boolean, null, undefined):
const a = 5;
const b = '5';
console.log(a === b); // false,类型不同
console.log(a == b); // true,松散相等会进行类型转换
浅比较对象
对于简单对象,可以通过遍历属性进行浅比较:

function shallowCompare(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every(key => obj1[key] === obj2[key]);
}
const objA = { x: 1, y: 2 };
const objB = { x: 1, y: 2 };
console.log(shallowCompare(objA, objB)); // true
深比较对象
递归实现深度比较,处理嵌套对象:
function deepCompare(obj1, obj2) {
if (obj1 === obj2) return true;
if (typeof obj1 !== 'object' || obj1 === null ||
typeof obj2 !== 'object' || obj2 === null) {
return false;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every(key => {
if (!keys2.includes(key)) return false;
return deepCompare(obj1[key], obj2[key]);
});
}
const objC = { x: 1, y: { z: 2 } };
const objD = { x: 1, y: { z: 2 } };
console.log(deepCompare(objC, objD)); // true
特殊案例处理
比较数组时需要注意顺序:

function compareArrays(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
return arr1.every((item, index) => item === arr2[index]);
}
console.log(compareArrays([1, 2], [1, 2])); // true
console.log(compareArrays([1, 2], [2, 1])); // false
使用现成工具库
Lodash 等库提供了完善的比较方法:
// 使用 lodash 的 isEqual
const _ = require('lodash');
console.log(_.isEqual({a: 1}, {a: 1})); // true
性能优化建议
对于大型对象比较,可以考虑:
- 先比较引用地址
- 比较属性数量
- 使用 Map 缓存比较结果
- 对于特定场景可以实现哈希比较
根据实际需求选择合适的比较方式,浅比较性能更好但不够彻底,深比较更准确但消耗更多资源。






