浅拷贝和深拷贝
作者:互联网
浅拷贝
function copy(obj) {
let newobj = {}
for (let i in obj) {
newobj[i] = obj[i]
}
return newobj
}
let obj1 = {
name: '小米',
age: 2,
}
let obj2 = copy(obj1)
obj2.name = '小红'
console.log(obj1)
console.log(obj2)
深拷贝
function copy(obj) {
let newobj = {}
for (let i in obj) {
if (obj[i] instanceof Object) {
newobj[i] = copy(obj[i])
} else {
newobj[i] = obj[i]
}
}
return newobj
}
let obj1 = {
name: '小米',
age: 2,
girlFriend: {
name: '小红'
}
}
let obj2 = copy(obj1)
obj2.girlFriend.name = '小花'
console.log(obj1)
console.log(obj2)
标签:obj1,obj2,obj,name,newobj,let,拷贝 来源: https://www.cnblogs.com/GFM0518/p/16592595.html