深拷貝 手寫深拷貝
阿新 • • 發佈:2020-12-28
技術標籤:javascript
手寫深拷貝
const obj1 = {
age : 20,
name: "xxx",
address: {
city: "beijing"
},
arr:["a","b","c"],
}
const obj2 = deepClone(obj1)
obj2.address.city = "shanghai"
console.log(obj1.address.city)
function deepClone(obj = { }){
if(typeof obj !=="object" || obj == null){
return obj
}
//初始化返回結果
let result
if(obj instanceof Array){
result = []
} else {
result = {}
}
for(let key in obj){
//保證 key 不是原型的屬性
if(obj.hasOwnProperty(key){
//遞迴
result[key] = deepClone(obj[key])
}
}
//返回結果
return result
}