// prototype 方法 // 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."); }
Array.prototype.equals = function(array) { if (!array) { returnfalse; } if (this.length !== array.length) { returnfalse; } for (var i = 0; i < this.length; i++) { if (this[i] instanceofArray && array[i] instanceofArray) { if (!this[i].equals(array[i])) { returnfalse; } } elseif (this[i] !== array[i]) { returnfalse; } } returntrue; }
Object.prototype.equals = function(object2) { //For the first loop, we only check for types for (propName inthis) { //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)) { returnfalse; } //Check instance type elseif (typeofthis[propName] != typeof object2[propName]) { //Different types => not equal returnfalse; } } //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)) { returnfalse; } elseif (typeofthis[propName] != typeof object2[propName]) { returnfalse; } //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] instanceofArray && object2[propName] instanceofArray) { // recurse into the nested arrays if (!this[propName].equals(object2[propName])) returnfalse; } elseif (this[propName] instanceofObject && object2[propName] instanceofObject) { // recurse into another objects //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named ""+propName+"""); if (!this[propName].equals(object2[propName])) returnfalse; } //Normal value comparison for strings and numbers elseif(this[propName] != object2[propName]) { returnfalse; } } //If everything passed, let's say YES returntrue; }