一天一题:手写一个深拷贝

290 阅读1分钟
    function isObject(obj) {
        return Object.prototype.toString.call(obj) === '[object Object]'
    }
    function deepCopy(source) {
        // 判断参数是对象还是数组来初始化返回值
        let res = Array.isArray(source) ? [] : {};
        // 循环参数对象的key
        for (let key in source) {
            // 如果该key属于参数对象本身
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                // 如果该key的value值是对象,递归调用深拷贝方法进行拷贝
                if (isObject(source[key])) {
                    res[key] = deepCopy(source[key]);
                } else {
                    // 如果该key的value值不是对象,则把参数对象key的value值赋给返回值的key
                    res[key] = source[key];
                }
            }
        }
        // 返回返回值
        return res;
    };