码迷,mamicode.com
首页 > 其他好文 > 详细

深拷贝

时间:2020-06-21 09:46:57      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:ret   返回   clone   ons   jin   深拷贝   拷贝   turn   res   

function deepClone(obj={}){
if (typeof obj !== "object" || obj == null) {
// 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;
}
const obj1 = {
name: ming,
address:{
city: beijing
},
arr:[1,2,3]
}
const obj2 = deepClone(obj1);
obj2.address.city = hangzhou
console.log(obj1.address.city); // beijing

 

深拷贝

标签:ret   返回   clone   ons   jin   深拷贝   拷贝   turn   res   

原文地址:https://www.cnblogs.com/liangzhixiaolaohu/p/13171128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!