const isEqualTwoObjects = (firstObj, secondObj) => {
// 0. 如果这两个对象指向同一个引用
if (firstObj === secondObj) {
return true
}
// 1. 第一步拿到这两个对象的 键
const firstObjKeys = Object.getOwnPropertyNames(firstObj)
const secondObjKeys = Object.getOwnPropertyNames(secondObj)
// 2. 判断键 长度是否一致
if (firstObjKeys.length !== secondObjKeys.length) {
return false
}
// 3. 判断 键名 是否相同
const set = new Set(firstObjKeys)
const bool = secondObjKeys.every(item => set.has(item))
if (!bool) {
return false
}
const getType = value => {
const result = Object.prototype.toString.call(value).split(' ')
const str = result[1]
const len = str.length
const type = str.substring(0, len - 1).toLowerCase()
return type
}
// 4. 进行比较判断每个属性的值是否相等
for (let i = 0; i < firstObjKeys.length; i++) {
const item = firstObjKeys[i]
const firstObjValue = firstObj[item]
const secondObjValue = secondObj[item]
const firstObjValueType = getType(firstObjValue)
const secondObjValueType = getType(secondObjValue)
if (firstObjValueType !== secondObjValueType) {
return false
}
if (firstObjValueType === 'function' || firstObjValueType === 'array') {
if (firstObjValue.toString() !== secondObjValue.toString()) {
return false
}
} else if (firstObjValueType === 'object') {
if (!isEqualTwoObjects(firstObjValue, secondObjValue)) {
return false
}
} else if (firstObjValue !== secondObjValue) {
return false
}
}
return true
}
js判断两个对象是否相等
最新推荐文章于 2023-09-25 16:55:55 发布