浅拷贝的几种方法[浅拷贝不能深层次拷贝]
let hd = {
name: '你好啊',
year: 12312
}
// 浅拷贝的几种方法
let obj = { ...hd }
obj.name = '132'
console.log(obj);//{name: '132', year: 12312}
console.log(hd);//{name: '你好啊', year: 12312}
方法2
let obj = Object.assign({}, hd)
obj.name = 'hello'
console.log(obj);//{name: 'hello', year: 12312}
console.log(hd);//{name: '你好啊', year: 12312}
深拷贝
案例1
let hd = {
name: 'hello',
year: 999,
user: {
name: "word"
}
}
function copy(object) {
let res = {}
for (const key in object) {
res[key] = typeof object[key] == 'object' ? copy(object[key]) : object[key]
}
return res
}
let data = copy(hd)
data.user.name = 'hello word'
console.log(JSON.stringify(data, null, 2));
console.log(JSON.stringify(hd, null, 2));
/*
{
"name": "hello",
"year": 999,
"user": {
"name": "hello word"
}
}
index.html:34 {
"name": "hello",
"year": 999,
"user": {
"name": "word"
}
}
*/
案例2
let hd = {
name: 'hello',
year: 999,
user: {
name: "word"
},
arr: [123, 456]
}
function copy(object) {
let res = object instanceof Array ? [] : {}
for (const [k,v] of Object.entries(object)) {
res[k] = typeof v== 'object' ? copy(v) : v
}
return res
}
let data = copy(hd)
data.arr.push(789)
console.log(JSON.stringify(data, null, 2));
console.log(JSON.stringify(hd, null, 2));
/*
{
"name": "hello",
"year": 999,
"user": {
"name": "word"
},
"arr": [
123,
456,
789
]
}
index.html:54 {
"name": "hello",
"year": 999,
"user": {
"name": "word"
},
"arr": [
123,
456
]
}
*/