深拷贝
const checkType = source
=> Object
.prototype
.toString
.call(source
).slice(8, -1)
const deepClone = source
=> {
let target
= null
const sourceType
= checkType(source
)
if (sourceType
=== 'Object') {
target
= {}
} else if (sourceType
=== 'Array') {
target
= []
} else {
return source
}
for (let key
in source
) {
if (source
.hasOwnProperty(key
)) {
target
[key
] = deepClone(source
[key
])
}
}
return target
}
深度比较
const checkType = source
=> Object
.prototype
.toString
.call(source
).slice(8, -1)
const deepCompare = (obj1
, obj2
) => {
if (checkType(obj1
) !== checkType(obj2
)) {
return false
}
if (obj1
=== obj2
) {
return true
}
if (Object
.keys(obj1
).length
!== Object
.keys(obj2
).length
) {
return false
}
for (let key
in obj1
) {
if (obj1
.hasOwnProperty(key
) && obj2
.hasOwnProperty(key
)) {
const res
= deepCompare(obj1
[key
], deepCompare(obj2
))
if (!res
) {
return false
}
}
}
return true
}
转载请注明原文地址:https://blackberry.8miu.com/read-31948.html