function deeoCopy(obj){
if(typeof obj === 'object'){
var res = obj instanceof Array ? [] : {}
for(var key in obj){
if(obj.hasOwnProperty(key)){
res[key] = typeof obj[key] == 'object' ? deeoCopy(obj[key]) : obj[key]
}
}
}else{
var res = obj
}
return res
}
function deepCopy(obj) {
// hash表,记录所有的对象的引用关系
let map = new WeakMap();
function dp(obj) {
let result = obj instanceof Array ? [] : {};
let keys = Object.keys(obj);
let existobj = map.get(obj);
//如果这个对象已经被记录则直接返回
if (existobj) {
return existobj;
}
map.set(obj, result);
for (let i = 0, len = keys.length; i < len; i++) {
let key = keys[i];
let temp = obj[key];
if (temp && typeof temp === 'object') {
result[key] = dp(temp);
} else {
result[key] = temp;
}
}
return result;
}
return dp(obj);
}
循环引用
let obj = {}
obj.a = {}
obj.a.b = obj.a
let obj = {}
obj.a = {}
obj.c = {}
obj.a.b = obj.c
obj.c.d = obj.a