深拷贝(学者说)

深拷贝

深拷贝:创建一个新的对象和数组,将原对象的各项属性的值(数组的所有元素)拷贝过来,是值而不是’引用

let obj = {
    
    
			 a:100,
			 b:200,
			arr:[44,55,66],
			 address:{
    
    
				city:'shanxi'
			}
		}
		var obj2 = deepClone(obj)
		obj2.address.city = "beijing"
		console.log(obj) // obj.address.city:"shanxi"
		console.log(obj2) // obj2.address.city:"beijing"
		
		function deepClone(obj = {
    
    }){
    
    
			// 先判断是不是数组或对象
			if(typeof obj != 'object' || obj == null){
    
    
				return obj
			}
			
			let result;
			
			if(result instanceof Array){
    
    
				return result = []
			}else{
    
    
				result = {
    
    }
			}
			
			
			for(var key in obj){
    
    
				// 判读key不是原型的属性
				if(obj.hasOwnProperty(key)){
    
    
					// 递归赋值
					result[key] = deepClone(obj[key])
				}
			}
			return result
		}

猜你喜欢

转载自blog.csdn.net/SSansui/article/details/111824261