浅拷贝 &&&深拷贝 实现
1.浅拷贝
//1.直接赋值给一个变量 //浅拷贝 //2.Object.assign() //浅拷贝 let obj4={} let obj5={money:50000} obj4.__proto__ = obj5 console.log(obj4) console.log(obj4.money) let obj6 ={name:'kebo',age:40} console.log(Object.assign(obj5,obj6)) //3.Array.prototype.concat() //浅拷贝 let arr =[1,2,'wede',{userName:'kobe'} ] let arr2 =arr.concat() //4.Array.prototype.slice() //浅拷贝 let arr3 =arr.slice() //5.JSON.parse(JSON.stringify()) //深拷贝 let arr4 =JSON.parse(JSON.stringify(arr))
2.深度拷贝的实现
//1. 判断数据的类型
function checkType(target){ return Object.prototype.toString.call(target).slice(8,-1) } //2.定义拷贝函数 function clone(target){ let result,targetType =checkType(target); if( targetType==='Object'){ result = {}; }else if(targetType ==="Array"){ result = []; }else{ return target; } //遍历数据结构中的每一项值 for(let i in target){ let value = target[i] if(checkType(value)==='Object' || checkType(value)==='Arrary'){ //继续遍历获取到的值 clone(value) }else{ result[i]=value } } return result; }