深拷贝

深拷贝就是要拷贝的对象内的所有引用类型的属性进行完整的拷贝;

也就是说拷贝出来的对象和原对象之间没有任何数据是共享的,所有的东西都是自己独占的一份;

三步实现深拷贝

第一步:判断入参是值类型还是引用类型,值类型直接返回

      		if(typeof obj !== 'object' || obj == null){
                return obj;
            }

第二步:判断是数组还是对象,用空变量接收结果

			if( obj instanceof Array){
                result = [];
            }else{
                result = {};
            }

第三步:递归调用

				if(obj.hasOwnProperty(key)){
                    // 递归调用
                    result[key] = deepClone(obj[key]);
                }

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝</title>
</head>
<body>
    <script>
        const obj1 = {
            name: "张三",
            address: {
                city: "北京",
                a:['1']
            }
        };
        //进行深拷贝
        const obj3 = deepClone(obj1);
        //修改深拷贝的数据
        obj3.address.city = "南京";
        //打印拷贝模板数据
        console.log('obj1',obj1);
        //打印修改后的深拷贝数据
        console.log('obj3',obj3);


        // obj = {}默认值
        function deepClone(obj = {}){
            // 判断传入的 obj 是不是数组或对象,不是直接返回 obj
            if(typeof obj !== 'object' || obj == null){
                return obj;
            }
            let result;
            // 判断是不是数组
            if( obj instanceof Array){
                result = [];
            }else{
                result = {};
            }
            for(let key in obj){
                // hasOwnProperty()方法:检测一个属性是否是对象的自有属性
                if(obj.hasOwnProperty(key)){
                    // 递归调用
                    result[key] = deepClone(obj[key]);
                }
            }
            return  result;
        }
    </script>
</body>
</html>

控制台输出

在这里插入图片描述