js deepCopy

function deepCopy(obj){
    if(obj===null || obj===undefined || typeof obj!=='object'){
        return obj;
    }
    if(Array.isArray(obj)){
        return obj.map(item=>deepCopy(item));
    }
    if(obj instanceof Object){
        const newObj={};
        for(let key in obj){
            if(obj.hasOwnProperty(key)){
                newObj[key]=deepCopy(obj[key])
            }
        }
        return newObj;
    }
    return obj;
}
// 进阶优化:解决循环引用 + 支持更多类
function deepCopy(obj, cache = new WeakMap()) {
    // 递归终止条件
    if (obj === null || obj === undefined || typeof obj !== 'object') {
        return obj;
    }

    // 若已拷贝过该对象,直接返回缓存的副本(解决循环引用)
    if (cache.has(obj)) {
        return cache.get(obj);
    }

    let newObj;

    // 处理 Date 类型
    if (obj instanceof Date) {
        newObj = new Date(obj);
        cache.set(obj, newObj);
        return newObj;
    }

    // 处理 RegExp 类型
    if (obj instanceof RegExp) {
        newObj = new RegExp(obj.source, obj.flags);
        cache.set(obj, newObj);
        return newObj;
    }

    // 处理 Array 类型
    if (Array.isArray(obj)) {
        newObj = [];
        cache.set(obj, newObj);
        obj.forEach((item, index) => {
            newObj[index] = deepCopy(item, cache);
        });
        return newObj;
    }

    // 处理 Map 类型
    if (obj instanceof Map) {
        newObj = new Map();
        cache.set(obj, newObj);
        obj.forEach((value, key) => {
            newObj.set(deepCopy(key, cache), deepCopy(value, cache));
        });
        return newObj;
    }

    // 处理 Set 类型
    if (obj instanceof Set) {
        newObj = new Set();
        cache.set(obj, newObj);
        obj.forEach(value => {
            newObj.add(deepCopy(value, cache));
        });
        return newObj;
    }

    // 处理普通对象
    if (obj instanceof Object) {
        newObj = {};
        cache.set(obj, newObj); // 先缓存,避免递归中再次引用当前对象
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                newObj[key] = deepCopy(obj[key], cache);
            }
        }
        return newObj;
    }

    return obj;
}

 

posted @ 2025-12-25 15:25  howhy  阅读(29)  评论(0)    收藏  举报