美文网首页
2019-05-03

2019-05-03

作者: 小红帽哟 | 来源:发表于2019-05-03 16:32 被阅读0次

    深拷贝

    利用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;

    }

    相关文章

      网友评论

          本文标题:2019-05-03

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