原理:通过对象合并,再转字符串,判断是否相等
优点:简单
缺点:不适用所有场景。如果是连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
}
本文探讨了两种比较JavaScript对象的方法。一种是通过对象合并并转换为字符串进行比较,适用于基本类型属性的简单对比。另一种是递归函数实现的深度比较,能够处理嵌套对象,确保结构与属性完全一致。
1591

被折叠的 条评论
为什么被折叠?



