原理:通过对象合并,再转字符串,判断是否相等
优点:简单
缺点:不适用所有场景。如果是连key值的顺序和属性数都要相等,则不适用
let obj = {
test:1,
test2:2,}
let obj2={
test:3,
test2:2
}
console.log( JSON.stringify(Object.assign({}, obj , obj )) ==JSON.stringify(Object.assign({}, obj, obj2)))
正统方法
// 两个对象比较
function compareDeepObj (source, target) {
if (!source || !target || typeof source !== 'object' || typeof target !== 'object') {
return false
}
for (let k in source) {
if (typeof source[k] === 'object' && typeof target[k] === 'object') {
compareDeepObj(source[k], target[k])
} else if ((typeof source[k] === 'object' && typeof target[k] !== 'object') || (typeof source[k] !== 'object' && typeof target[k] === 'object')) {
return true
} else {
if (source[k] !== target[k]) {
return true
}
}
}
return false
}