js封装深拷贝

只谈情不闲聊 提交于 2020-01-29 05:46:45
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			function checkType(data){
				return Object.prototype.toString.call(data).slice(8,-1);//[object Object]
			}
			
			function deepCopy(data){//拷贝的都是对象数据类型
				let dataType = checkType(data);
				let result;
				if(dataType == 'Array'){
					result = [];
				}else if(dataType == 'Object'){
					result = {};
				}else{
					result = data;
					return result;
				}
				
				for(let key in data){
					if(checkType(data[key]) == 'Array' || 'Object'){
						result[key] = deepCopy(data[key]);
					}else{
						result[key] = data[key];
					}
				}
				return result;
			}
			
			let data ={
				name:'zly',
				age:32,
				movie:{
					name:'乘风破浪',
					timeLong:120,
					main:['邓超','彭于晏'],
				}
			}
			
			let result = deepCopy(data)
			console.log(result);
			
			
			result.movie.main[0] = '赵丽颖';
			console.log(data);//data中的数据并没有被改变
		</script>
	</body>
</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!