深拷贝,浅拷贝

浅拷贝:

Object.assign()、Array.slice()、JSON.parse(JSON.stringfy(obj))

深拷贝:

 

function  qCopy(source) {
    if(typeof source!=='object' && source!==null) return source; //基本类型 返回自身
    let target;
    if(Array.isArray(source)){ //兼容数组和对象
        target=[];
    }else{
        target={};
    }
    for(let key in source){
        if(Object.prototype.hasOwnProperty.call(source,key)){
            if(typeof source[key]=='object'){ //属性值为引用类型
                target[key]= qCopy(source[key]);
            }else{
                target[key]=source[key];
            }
            
        }
    }
    return target;
}

 

posted @ 2021-08-10 20:09  阿兰儿  阅读(23)  评论(0编辑  收藏  举报