javascript实现深拷贝

147 阅读1分钟
function isArray(obj){
    //return obj instanceof Array;
    //return Object.prototype.toString.call(val) === '[object Array]';
    return obj.constructor === Array
}

function isObject(obj){
    //return obj.constructor === Object || obj.constructor === Array
     return typeof obj === 'object' && obj !==null
}

function deepCopy(obj){
    let newObj = isArray(obj) ? [] : {};
    for(let val in obj){
        if(isObject(obj[val])){
            newObj[val] = deepCopy(obj[val]);
        }else{
            newObj[val] = obj[val];
        }
    }
    return newObj;
}
function deepCopy2(obj){
    return JSON.parse(JSON.stringify(obj))
}
let test = {a: 1, b:2 ,c : {a:100}, d: [1,2,3]}
let res = deepCopy(test)
let res2 = deepCopy2(test)