其他分享
首页 > 其他分享> > 手写对象深度拷贝

手写对象深度拷贝

作者:互联网

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);

 

标签:obj1,obj,deepClone,let,result,key,深度,手写,拷贝
来源: https://www.cnblogs.com/MaX666999/p/14439095.html