js 深拷贝

let obj = {
name: '张三',
user: {
name: 'hdcms',
},
data: [],
};

function copy(object) {
let obj = object instanceof Array ? [] : {};
for (const [k, v] of Object.entries(object)) {
obj[k] = typeof v == 'object' ? copy(v) : v;
}
return obj;
}

let ls = copy(obj);
ls.data.push('李四');
console.log(JSON.stringify(ls, null, 2));
console.log(JSON.stringify(obj, null, 2));
posted @ 2023-10-19 10:23  外行的小白  阅读(5)  评论(0编辑  收藏  举报