1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function deepClone(source, clonedMap = new Map()) { if(typeof source !== "object" || source == null){ return source; }
if(clonedMap.has(source)){ return clonedMap.get(source); }
const target = Array.isArray(source) ? [] : {};
clonedMap.set(source, target);
for(const key in source){ if( typeof source[key] === "object" && source[key] !== null){ target[key] = deepClone(source[key], clonedMap); } else { target[key] = source[key]; } } return target; }
const obj = {a: 1, b: {c: 2}} obj.self = obj;
const copy = deepClone(obj);
console.log(copy);
|