Identifying the equality of arrays in JavaScript can be a challenging task. The typical comparison operator, ==, will not suffice in this scenario. Instead, we delve into the realm of object comparison, which requires a more nuanced approach.
The straightforward method for comparing arrays is to iterate through their elements and verify their equality. Here's how it's done:
Array.prototype.equals = function (array) { if (!array) return false; if (this === array) return true; if (this.length !== array.length) return false; for (let i = 0, l = this.length; i < l; i++) { if (this[i] instanceof Array && array[i] instanceof Array) { if (!this[i].equals(array[i])) return false; } else if (this[i] !== array[i]) return false; } return true; };
Objects present a unique challenge when comparing. Two object instances, even with identical properties, will never be considered equal due to their distinct class instances. However, if the focus is solely on data comparison, this is still possible:
Object.prototype.equals = function (object2) { for (const propName in this) { if (this.hasOwnProperty(propName) !== object2.hasOwnProperty(propName)) return false; if (typeof this[propName] !== typeof object2[propName]) return false; } for (const propName in object2) { if (this.hasOwnProperty(propName) !== object2.hasOwnProperty(propName)) return false; if (typeof this[propName] !== typeof object2[propName]) return false; if (!this.hasOwnProperty(propName)) continue; if (this[propName] instanceof Array && object2[propName] instanceof Array) { if (!this[propName].equals(object2[propName])) return false; } else if (this[propName] instanceof Object && object2[propName] instanceof Object) { if (!this[propName].equals(object2[propName])) return false; } else if (this[propName] !== object2[propName]) { return false; } } return true; };
For nested arrays, Samy Bencherif's functions provide an efficient method for searching and comparing specific objects within multidimensional arrays: https://jsfiddle.net/SamyBencherif/8352y6yw/.
The above is the detailed content of How Do I Compare Arrays and Objects for Equality in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!