简单写一个深拷贝

99 阅读1分钟

写一个经常用到的深拷贝,而不是单纯的调用api,JSON.parse(JSON.stringify(copyObj))只适用于简单的深拷贝,如果对象里有函数,函数无法被拷贝下来,无法拷贝copyObj对象原型链上的属性和方法

function deepClone(data) {
    if(typeof data == 'object'){
        if(Array.isArray(data)){
    let obj = []
            data.forEach(item=>{
                obj.push(deepClone(item))
            })
            return obj
        }else{
        let obj = {}
            for(i in data){
                obj[i] = deepClone(data[i])
            }
            return obj
        }
    } else{
        return data
    }
}

方案二比较全
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
 
    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }
 
    if (obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepClone(item);
            return arr;
        }, []);
    }
 
    if (obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepClone(obj[key]);
            return newObj;
        }, {});
    }
}