面试官:写一个深拷贝叭。

329 阅读1分钟

需要注意的点

  • 循环引用,使用WeakMap用来优化GC策略
  • RegExp和Date情况

看代码

function deepClone(obj, hash = new WeakMap()) {
            if (obj instanceof RegExp) return new RegExp(obj);
            if (obj instanceof Date) return new Date(obj);

            if (typeof obj !== 'object' || obj === null) return obj;

            if (hash.has(obj)) return hash.get(obj);

            let t = obj.constructor();

            hash.set(obj, t);

            for (let i in obj) {
                if (obj.hasOwnProperty(i)) {
                    t[i] = deepClone(obj[i], hash)
                }
            }
            return t;
        }

        //测试
        let a = {
            a: 'hello',
            b: {
                a: 'ee',
                b: [1, 3, function () { return 123 }]
            },
            c: 'wer',
            d: [4, 3, 5, 6, 3]
        }

        let b = deepClone(a)
        b.b.b[1] = 5;
        b['b']['b'][2] = () => {
            return 789
        }

        console.log(a.b.b[2]());
        console.log(b);
        console.log(a);


记录记录!