手写对象深度拷贝

function deepClone(obj = {}) {
    if ( typeof obj !== 'object' || typeof obj == null ) {
        return obj
    }

    let result;
    if ( obj instanceof Array ) {
        result = [];
    } else {
        result = {};
    }

    for(let key in obj) {
        if (obj.hasOwnProperty(key)) {
            result[key] = deepClone(obj[key])
        }
    }
    return result;
}

let obj1 = {
    name:'x',
    age:'18'
};
const obj2 = deepClone(obj1);
console.log(obj2);

 

posted on 2021-02-24 01:29  I666999  阅读(20)  评论(0编辑  收藏  举报

导航