深拷贝
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)) { // in会遍历数组原型上的属性
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
}