Shallowcopy和deepcopy浅拷贝就是创建一个新的对象,这个对象拥有原对象的属性值的副本。如果属性是基本类型,则复制基本类型的值,如果属性是引用类型,则复制内存地址。如果不进行深拷贝,如果其中一个对象改变了该对象的值,就会影响另一个对象的值。深拷贝就是从内存中对一个对象进行完整的拷贝,从堆内存中开辟一块新的区域来存放新的对象,在不影响原对象的情况下修改新的对象。1.JSON.parse(JSON.stringify(obj))一般情况下,对于普通对象需要进行深拷贝。此方法可用于深度复制操作。这是最简单的深拷贝方法,代码量最少。leta={a:1,b:2}letb=JSON.parse(JSON.stringify(a))a.a=11console.log(a)//{a:1,b:2}console.log(b)//{a:11,b:2}1.1JSON.parse(JSON.stringify(obj))深浅拷贝缺陷leta={name:'Jack',age:18,hobbit:['sing',{type:'sports',value:'run'}],score:{math:'A',},run:function(){},walk:undefined,fly:NaN,cy:null,date:new日期()}letb=JSON.parse(JSON.stringify(a))console.log(b)//{//age:18,//cy:null,//date:"2022-05-15T08:04:06.808Z"//fly:null,//hobbit:(3)["dance","sing",{...}],//name:"Jack",//score:{math:"A"},//}无法获取值为undefined的key;如果对象中有函数,则不能复制该函数;copyObj对象原型链上的属性和方法不能被复制;该对象被转换为日期字符串。2.普通递归函数实现深拷贝函数deepClone(source){if(typeofsource!=='object'||source==null){returnsource;}consttarget=Array.isArray(source)?[]:{};for(constkeyinsource){if(Object.prototype.hasOwnProperty.call(source,key)){if(typeofsource[key]==='object'&&source[key]!==null){目标[键]=deepClone(源[键]);}else{目标[键]=源[键];}}}returntarget;}2.1解决循环引用和符号类型functioncloneDeep(source,hash=newWeakMap()){if(typeofsource!=='object'||source===null){returnsource;}if(hash.has(source)){returnhash.get(source);}const目标=数组。isArray(来源)?[]:{};Reflect.ownKeys(source).forEach(key=>{constval=source[key];if(typeofval==='object'&&val!=null){target[key]=cloneDeep(val,hash);}}else{target[key]=val;}})returntarget;}3.兼容多种数据类型constdeepClone=(source,cache)=>{if(!cache){cache=newMap()}if(sourceinstanceofObject){//不考虑跨iframeif(cache.get(source)){returncache.get(source)}letresultif(sourceinstanceofFunction){if(source.prototype){//有原型就是普通函数result=function(){returnsource.apply(this,arguments)}}else{result=(...args)=>{returnsource.call(undefined,...args)}}elseif(sourceinstanceofArray){result=[]}elseif(sourceinstanceofDate){result=newDate(source-0)}elseif(sourceinstanceofRegExp){result=newRegExp(source.source,source.flags)}else{result={}}cache.set(source,result)for(letkeyinsource){if(source.hasOwnProperty(key)){result[key]=deepClone(source[key],cache)}}returnresult}else{returnsource}}4.jQuery.extend()方法可以使用$.extend进行深贝$。扩展(深拷贝,目标,object1,[objectN])//第一个参数为true,就是深贝leta={a:1,b:{d:8},c:[1,2,3]};letb=$.扩展(真,{},一个);console.log(a.b.d===b.b.d);//false4.1jQuery.extend源码jQuery.extend=jQuery.fn.extend=function(){varoptions,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;//处理深拷贝情况if(typeoftarget==="boolean"){deep=target;//跳过布尔值和目标target=arguments[i]||{};我++;}//当目标是字符串或其他东西(可能在深层复制中)时处理情况if(typeoftarget!=="object"&&!jQuery.isFunction(target)){target={};}//如果只传递一个参数,则扩展jQuery本身if(i===length){target=this;我-;}for(;i
