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 33 34 35 36 37 38 39 40 41
| function deepClone(obj, hash = new WeakMap()) { if (!obj) return obj let clone;
if(hash.has(obj)){ return hash.get(obj) }
if (obj instanceof Set) { return new Set([...obj]) } else if (obj instanceof Map) { return new Map([...obj]) } else if (obj instanceof WeakMap) { throw 'weakmap类型未作处理' } else if (typeof obj === 'function') { return obj } else if (obj instanceof Array) { clone = []; hash.set(obj, clone) obj.forEach(item => { clone.push(deepClone(item, hash)) }) } else if (typeof obj !== 'object') { return obj } else { clone = {}; hash.set(obj, clone) Object.getOwnPropertyNames(obj).forEach(propNames => { clone[propNames] = deepClone(obj[propNames],hash) }) Object.getOwnPropertySymbols(obj).forEach(syb => { clone[Symbol(syb.description)] = deepClone(obj[syb],hash) }) } return clone }
|