/**
* 深拷贝
*/
const obj1 = {
age: 18,
name: "xxx",
address: {
city: "beijing"
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1);
console.log(obj2);
obj2.address.city = '上海';
console.log(obj1.address.city);
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
// 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
}
// 浅拷贝
// const obj1 = {
// age: 18,
// name: "xxx",
// address: {
// city: "beijing"
// },
// arr: ['a', 'b', 'c']
// }
// const obj2 = obj1;
// obj2.address.city = '上海';
// console.log(obj1.address.city);
谢谢收看,欢迎关注分享留言哦!如有侵权问题请联系作者删除。