手写深拷贝
主要分四步:
1、判断数据类型
2、初始化返回的数据格式
3、判断当前拷贝的属性是否是其原型上的属性
4、递归逐层调用
function deepClone(obj = {}) {
// 判断数据类型
if (typeof obj !== 'object' || obj == null) {
return obj;
}
// 初始化返回结果
let result;
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj){
// 保证key不是原型属性
if (obj.hasOwnProperty(key)) {
// 递归调用
result[key] = deepClone(obj[key])
}
}
return result;
}