深拷贝的循环引用问题
作者:xie392地址:https://v.douyin.com/iexSuQJj/更新时间:2024-12-21
案例代码
1const obj = {2arr: [1,2,3],3a: 44}56obj.sub = obj7obj.arr.push(obj)89function deepClone(value) {10// WeakMap 可以用来存储对象,因为它可以被垃圾回收11const cache = new WeakMap()1213function _deepClone(value) {14if(value === null || typeof value !== 'object') {15return value16}1718if(cache.has(value)) {19return cache.get(value)20}2122const cloneObj = Array.isArray(value) ? [] : {}23cache.set(value, cloneObj)24for(let key in value) {25if(value.hasOwnProperty(key)) {26cloneObj[key] = _deepClone(value[key])27}28}29return cloneObj30}3132return _deepClone(value)33}343536const newArr = deepClone(obj)37console.log(newArr.arr !== obj.arr) // true38console.log(newArr.sub !== obj.sub) // true39console.log(newArr.arr[3] !== obj) // true
输出结果:
1true2true3true
目录