文章目录
浅拷贝
Object.assign
let Person = {
name: '123',
arr:[1,2,3]
}
var person = {}
// 对于引用类型只是浅拷贝
Object.assign(person, Person) //浅拷贝
person.name = "111"
person.arr.push(456)
console.log(person === Person) //false
console.log(person.name) //111
console.log(Person.name) //123 // 没同步
console.log(Person.arr); // [ 1, 2, 3, 456 ] 同步了
深拷贝
JSON
obj = {
name: "tom",
id: 18,
goods: {
id: 123
},
list: [1, 23, 1, 4]
}
function deepClone(obj) {
let result = JSON.parse(JSON.stringify(obj));
return result;
}
console.log(deepClone(obj))
存在问题 无法拷贝function undefined
第三方库lodash
手写一个深拷贝
let obj = {
name: '123',
arr: [1, 2, 3],
userdata: {
likes: ["玩", "ci"]
}
}
function deepCopy(obj){
let objClone = Array.isArray(obj)?[]:{};
if(obj && typeof obj =="object"){
for(key in obj){
if(typeof obj[key]=="object"){
objClone[key]=deepCopy(obj[key])
}else{
objClone[key] = obj[key]
}
}
}
return objClone;
}
let newObj=deepCopy(obj)
newObj.userdata.likes.push("456")
newObj.userdata.likes[0]="和"
console.log(newObj,obj);