美文网首页
有关深拷贝

有关深拷贝

作者: 木羽木羽女口生 | 来源:发表于2020-12-02 22:06 被阅读0次
/**
*深拷贝
*/

const obj1 = {
    age:20,
    name:'xxx',
    adress:{
        city:'beijing'
    },
    arr:['a','b','c']
}

const obj2= deepClone(obj1)

obj2.address.city = 'shanghai'
console.log(obj1.address.city)


/**
 *
 *深拷贝
 * @param {Object} obj 要拷贝的对象
 */
function deepClone(obj = {}){
    if(typeof obj !== 'object' || obj == null){
        //如果obj 是null,或不是对象和数组,直接返回
        return {}
    }

    //初始化返回结果
    let result
    if(result instanceof Array){
        result = []
    }else{
        result = {}
    }

    for (const key in obj) {
        //保证key 不是原型的属性
        if (obj.hasOwnProperty(key)) {
            //递归的调用!!
            result[key]  = deepClone(obj[key]);
            
        }
    }

    return result
}

相关文章

网友评论

      本文标题:有关深拷贝

      本文链接:https://www.haomeiwen.com/subject/ylzuwktx.html