判断json 对象是否相同的方法
var arr = [1, 2, 3, { a: 1, b: 4},[2,8]] var arr2 = [1, 2, 3, { b: 4, a: 1 }, [2, 8]] Array.prototype.equals = function (array) { if (!array) return false; 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)) { console.log("数组中检测到数组", this[i], array[i]) // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if ((this[i] instanceof Object && array[i] instanceof Object)) { console.log("数组中检测到对象") 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; } Object.prototype.equals = function (object2) { // console.log(object2) for (var propName in this) { // console.log("对象值不一样") if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) { return false; } //Check instance type else if (typeof this[propName] != typeof object2[propName]) { return false; } } //Now a deeper check using other objects property names for (propName in object2) { 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; 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) { //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]) { console.log("对象值不一样", this[propName], object2[propName]) return false; } } //If everything passed, let's say YES return true; } console.log(arr.equals(arr2))
注意:数组的比较注意下标 如果位置不一样值一样 仍return false