如何判断两个数组是否完全相等,如何判断两个对象是否完全相等
记录一下~
也是sku库存配置中用到的
每次往数组里插入值时,都要判断之前选中的数组里面是否已经存在了这个数组对象
arrayEquals(array1, array2) {
// if array1 or array2 is a falsy value, return
if (!array1 || !array2)
return false;
// compare lengths - can save a lot of time
if (array1.length != array2.length)
return false;
for (var i = 0, l = array1.length; i < l; i++) {
// Check if we have nested arrays
if (array1[i] instanceof Array && array2[i] instanceof Array) {
// recurse into the nested arrays
if (!this.arrayEquals(array1[i], array2[i]))
return false;
} else if (array1[i] instanceof Object && array2[i] instanceof Object) {
// 比较含有的对象是否相等
if (!this.objectEquals(array1[i], array2[i]))
return false;
} else if (array1[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
},
objectEquals(object1, object2) {
//For the first loop, we only check for types
for (let propName in object1) {
//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 (object1.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
//Check instance type
else if (typeof object1[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
}
//Now a deeper check using other objects property names
for (let 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 (object1.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
} else if (typeof object1[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 (!object1.hasOwnProperty(propName))
continue;
//Now the detail check and recursion
//This returns the script back to the array comparing
/**REQUIRES Array.equals**/
if (object1[propName] instanceof Array && object2[propName] instanceof Array) {
// recurse into the nested arrays
if (!this.arrayEquals(object1[propName], object2[propName]))
return false;
} else if (object1[propName] instanceof Object && object2[propName] instanceof Object) {
// recurse into another objects
if (!this.objectEquals(object1[propName], object2[propName]))
return false;
}
//Normal value comparison for strings and numbers
else if (object1[propName] != object2[propName]) {
return false;
}
}
//If everything passed, let's say YES
return true;
}