JavaScript深度比较两个对象是否相等
作者:半夏时间:2026-10-28 21:57:20浏览:75
本文介绍在JavaScript中比较两个对象是否相等的方法。由于JS原生缺乏类似Python cmp()的内置函数,本文通过自定义cmp函数实现深度比较,涵盖类型检查、原型链及属性遍历,帮助开发者判断对象数据一致性。
JavaScript对象相等比较方法
本文详细介绍了一种在JavaScript中判断两个对象是否相等的具体实现方案,供开发者参考使用。
Python语言提供了cmp()内置函数用于比较数组、序列或字典等对象的数据内容,但JavaScript并未提供类似的直接实现。本文通过编写自定义JS代码,从多个维度对JS对象进行比较,从而判定两个对象是否相等。
cmp = function( x, y ) {
// If both x and y are null or undefined and exactly the same
if ( x === y ) {
return true;
}
// If they are not strictly equal, they both need to be Objects
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {
return false;
}
//They must have the exact same prototype chain,the closest we can do is
//test the constructor.
if ( x.constructor !== y.constructor ) {
return false;
}
for ( var p in x ) {
//Inherited properties were tested using x.constructor === y.constructor
if ( x.hasOwnProperty( p ) ) {
// Allows comparing x[ p ] and y[ p ] when set to undefined
if ( ! y.hasOwnProperty( p ) ) {
return false;
}
// If they have the same strict value or identity then they are equal
if ( x[ p ] === y[ p ] ) {
continue;
}
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( typeof( x[ p ] ) !== "object" ) {
return false;
}
// Objects and Arrays must be tested recursively
if ( ! Object.equals( x[ p ], y[ p ] ) ) {
return false;
}
}
}
for ( p in y ) {
// allows x[ p ] to be set to undefined
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {
return false;
}
}
return true;
};
具体使用方式如下:
objA={
a:'123',
b:'456'
};
objB={
a:'123',
b:'000'
};
var isEqual= cmp(objA, objB);
console.log(isEqual); // false 不相同
希望本文提供的解决方案能对您的JavaScript编程工作有所帮助。
作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
