JS手写一个简单的深拷贝

504 阅读1分钟
     var deepClone = (obj) =>{
		 let newObj;
		 if(obj instanceof Array){
			 newObj = []
			 for(let i in obj){
				 if(obj[i] instanceof Array){
					 newObj[i] = deepClone(obj[i])
				 }else{
					  newObj[i] = obj[i]
				 }
			 }
		 }else if(obj instanceof Object){
			 newObj = {}
			 for(let i in obj){
			 	 if(obj[i] instanceof Object){
			 		 newObj[i] = deepClone(obj[i])
			 	 }else{
			 		 newObj[i] = obj[i]
			 	 }
			 }
		 }else{
			 return obj
		 }

		 return newObj
	 }

特征 1:可用于拷贝数组和对象

特征 2: 只能拷贝可枚举属性,原型链上的属性不支持