2019-05-03

深拷贝



利用JSON.stringify和JSON.parse实现深度拷贝


function copy(obj) {

  let temp=JSON.parse(JSON.stringify(obj));

  return temp;

}



自写函数实现深拷贝


let same=[];

function clone(obj) {

if(typeof(obj) !=="object"||!obj){

//基本类型的数据:null,number,string,boolean,undefined

// function

        return obj;

    }

if(same.indexOf(obj)>-1){

//防止形成circle,比如obj={a:obj}

        return null;

    }

same.push(obj);

    let temp={}.toString.call(obj);

    let result;

    if(temp==='[object Array]'){

//数组

        result=[];

        obj.forEach((item,index)=>{

        result[index]=clone(item);

        });

    }

if(temp==='[object Object]'){

//对象

        result={};

        Object.keys(obj).forEach((key)=>{

        result[key]=clone(obj[key]);

        })

}

return result;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容