js对象的浅拷贝
使用Object.assign或者…展开语法
let user = {
name: 'SJ',
url: 'www.baidu.com'
};
// 浅拷贝 复制值
let obj = Object.assign({}, user);
let obj1 = { ...user }
console.log(obj)
console.log(obj1)
js对象的深拷贝
在对Object进行深拷贝的过程中需要考虑对象的属性值是否包含数组或者对象
// 深拷贝(对象的属性中包含对象或者数组的情况)
let obj = {
name: 'SJ',
health: {
heart: 72
},
list: []
}
function copy(obj) {
let res = obj instanceof Array ? [] : {};
for (const [k, v] of Object.entries(obj)) {
res[k] = typeof v == "object" ? copy(v) : v;
}
return res;
}
let new_obj = copy(obj);
new_obj.list.push("arr");
console.log(JSON.stringify(obj, null, 2));
console.log(JSON.stringify(new_obj, null, 2));
// 结果如下
{
"name": "SJ",
"health": {
"heart": 72
},
"list": []
}
{
"name": "SJ",
"health": {
"heart": 72
},
"list": [
"arr"
]
}