深拷贝

作者: 酒暖花深Q | 来源:发表于2020-09-09 10:36 被阅读0次
     <script>
            const obj1 = {
                age:20,
                name:'lily',
                address:{
                    city:'beijing'
                },
                arr:['a','b','c']
            }
            // const obj2 = obj1;
            const obj2 =  deepClone(obj1);
            obj2.address.city = 'shanghai';
            // console.log(obj1.address.city); //shanghai
            console.log(obj1.address.city);  //beijing
    
            /*obj == obj1{} 要拷贝的对象*/ 
            function deepClone(obj = {}){
                // obj 不是对象或者为空直接返回
                if(typeof obj !== 'object' || obj == null){
                    return
                }
                //初始化返回结果
                let result;
                if(obj instanceof Array){
                    result = [];  
                }else{
                    result = {}
                }
    
                for(let key in obj){
                    // 保证key不是原型属性
                  if(obj.hasOwnProperty(key)){
                    //递归调用(函数通过名字调用自己本身)
                    result[key] = deepClone(obj[key])
                  }
                }
                //返回结果
                return result;
            }
            
        </script>
    

    相关文章

      网友评论

          本文标题:深拷贝

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