1.Map可以使用任意类型的key值,不限字符串,对象等。
2.WeakMap只能使用对象作为key值,是弱引用,当从WeakMap中移除时,会自动垃圾回收
3.Object只能用基本类型作为key值。
下面使用WeakMap解决深拷贝中对象循环引用问题
function deepClone (origin, weakMap = new WeakMap()) { if (origin == undefined || typeof origin != 'object') { return origin } if (origin instanceof Date) { return new Date(origin) } if (origin instanceof RegExp) { return new RegExp(origin) } const val = weakMap.get(origin) if (val) return val const target = new origin.constructor() weakMap.set(origin, target) for (let k in origin) { target[k] = deepClone(origin[k], weakMap) } return target }
测试代码:
let obj1 = {}
obj1.obj2 = obj1
let obj2 = deepClone(obj1)
console.log(obj2, 'obj2')