深克隆

95 阅读1分钟
        // 深克隆
        function deepClone(obj) {
            // 检查是否为对象
            if (!obj || typeof obj !== 'object') {
                return obj;
            }
            // 初始化一个数组或者对象
            const arr = obj instanceof Array ? [] : {};
            // 遍历对象或者数组
            for (const key in obj) {
                // 如果value还是对象就递归
                arr[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
            }
            return arr;
        }
        let obj = {
            name: 'luoxijie',
            age: 21,
            str: [1, 2, { a: 3 }],
        };
        let newObj = deepClone(obj);
        newObj.name = '罗熙杰';
        newObj.str = [1, 2, 3];
        console.log(obj);
        console.log(newObj);

结果:

        obj = {
            name: 'luoxijie',
            age: 21,
            str: [1, 2, { a: 3 }],
        };
        newObj = {
            name: '罗熙杰',
            age: 21,
            str: [1, 2, 3],
        };