Skip to content

深拷贝

简易版实现思路:

  • 使用递归
  • 考虑循环引用,使用 map 和 weakMap
  • 考虑对象 object 和数组 array
  • 考虑 null
  • 考虑其他复合对象:比如 Date、Mach 等

代码实现:

js
function deepClone(targrt, map = new Map()) {
    if (typeof targrt == "object" && targrt !== null) {
        const obj = Array.isArray(targrt) ? [] : {};
        if (map.get(targrt)) {
            return map.get(targrt);
        }
        map.set(targrt, obj);
        for (const key in targrt) {
            obj[key] = deepClone(targrt[key], map);
        }
        return obj;
    }
    return targrt;
}