JavaScript深度比较两个对象是否相等

作者:半夏

时间:2026-10-28

浏览:74

本文介绍在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编程工作有所帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章