JavaScript 中比较数组与对象是否相等的实现方法
本文详解JavaScript中基本类型与引用类型的区别,重点讲解如何判断两个数组或对象是否相等。通过JSON.stringify排序转换及封装深度比较函数,解决引用地址不同导致的比较失效问题,提供实用的代码示例。
JavaScript基本类型与引用类型的区别
在JavaScript中,所谓的“传值”机制主要涉及五种基本数据类型,包括null、undefined、boolean、number和string。
而“传引用”则针对引用数据类型,主要涵盖array(数组)和object(对象)。
基本数据类型的值具有不可变性,相比之下,引用数据类型的值是可以被修改的。
因此,在直接比较数组和对象时,结果通常返回false,除非比较的是同一份克隆数据的原始引用。
例如:var a = { name: "李四" }; var b = a;
通常我们将对象称为引用类型,以此与基本类型区分;由于对象值本质上是引用,所以对象的比较实际上是比较其引用的指向。只有当两个变量指向同一个基对象时,它们才被视为相等。
数组相等性的判断方法
1. 比较两个单独的数组是否相等
JSON.stringify(a1) == JSON.stringify(a2)
或者
a1.toString() == a2.toString()
若要判断两个数组是否相同,一种常见方法是将数组转换为字符串后进行比对。
如果目标是判断两个数组的元素内容是否相等,则:
JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort());
或者
[1,2,3].sort().toString() === [3,2,1].sort().toString();
判断两个数组是否相同,首先需要将数组进行排序,然后转换为字符串进行比较。
对象相等性的判断方法
2. 比较两个单独的对象是否相等
let cmp = ( 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;
};
以下参考了StackOverflow上大神封装的方法,可供学习参考:
1. 比较数组
// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l = this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
2. 比较对象
Object.prototype.equals = function(object2) {
//For the first loop, we only check for types
for (propName in this) {
//Check for inherited methods and properties - like .equals itself
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
//Return false if the return value is different
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
//Check instance type
else if (typeof this[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
}
//Now a deeper check using other objects property names
for(propName in object2) {
//We must check instances anyway, there may be a property that only exists in object2
//I wonder, if remembering the checked values from the first loop would be faster or not
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
else if (typeof this[propName] != typeof object2[propName]) {
return false;
}
//If the property is inherited, do not check any more (it must be equa if both objects inherit it)
if(!this.hasOwnProperty(propName))
continue;
//Now the detail check and recursion
//This returns the script back to the array comparing
/**REQUIRES Array.equals**/
if (this[propName] instanceof Array && object2[propName] instanceof Array) {
// recurse into the nested arrays
if (!this[propName].equals(object2[propName]))
return false;
}
else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
// recurse into another objects
//console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
if (!this[propName].equals(object2[propName]))
return false;
}
//Normal value comparison for strings and numbers
else if(this[propName] != object2[propName]) {
return false;
}
}
//If everything passed, let's say YES
return true;
}
总结
以上介绍了JavaScript中比较两个单独数组或对象是否相等的实例代码,希望对大家有所帮助。如有任何疑问,欢迎留言,小编会及时回复。感谢大家对本站的支持! 如果觉得本文对您有帮助,欢迎转载,烦请注明出处,谢谢!
JavaScript异步发送HTTP请求时怎么优雅地处理错误
2026-11-05 17:10:44
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
