deepMerge(...objs) {
const result = Object.create(null)
objs.forEach(obj => {
if (obj) {
Object.keys(obj).forEach(key => {
const val = obj[key]
if (isPlainObject(val)) {
// 递归
if (isPlainObject(result[key])) {
result[key] = deepMerge(result[key], val)
} else {
result[key] = deepMerge(val)
}
} else {
// 数组也要重新赋值 不然依然会引用到其他的
if (Array.isArray(val)) {
result[key] = [...val]
} else {
result[key] = val
}
}
})
}
})
console.log(result)
return result
}
isPlainObject(val) {
const toString = Object.prototype.toString
return toString.call(val) === '[object Object]'
}
deepMerge 参数,后面对象会覆盖前面的。