当前位置: 首页 > Web前端 > vue.js

前端常用的10个手写功能你都知道吗?

时间:2023-03-31 21:54:39 vue.js

楂樻ゼ鎷斿湴鑰岃捣锛屽湴鍩虹墷鍥猴紝鏂硅兘绔嬩簬涓嶈触涔嬪湴銆備粖澶╃粰澶у甯︽潵鐨勬槸10涓父鐢ㄧ殑JavaScript鎵嬪啓鍑芥暟锛岄噸瑕佺殑鍦版柟閮藉姞浜嗘敞閲娿€傛湁浜涙槸浠庡埆浜洪偅閲屽€熸潵鐨勶紝鏈変簺鏄嚜宸卞啓鐨勩€傚鏋滄湁涓嶅噯纭殑鍦版柟锛岃鎸囨銆?.闃叉姈鍔熻兘debounce(fn,delay){璁╁畾鏃跺櫒杩斿洖鍑芥暟(...args){if(timer){clearTimeout(timer)}timer=setTimeout(()=>{fn.apply(this,args)},delay)}}//娴嬭瘯鍑芥暟task(){console.log('runtask')}constdebounceTask=debounce(task,1000)window.addEventListener('scroll',debounceTask)澶嶅埗浠g爜2锛岃妭娴佸嚱鏁皌hrottle(fn,delay){letlast=0//鏈€鍚庤Е鍙戞椂闂磖eturn(...args)=>{constnow=Date.now()if(now-last>delay){last=nowfn.apply(this,args)}}}//娴嬭瘯鍑芥暟task(){console.log('runtask')}constthrottleTask=throttle(task,1000)window.addEventListener('scroll',throttleTask)copy浠g爜3,deepCopyfunctiondeepClone(obj,cache=newWeakMap()){if(typeofobj!=='object')returnobj//鏅€氱被鍨嬶紝鐩存帴杩斿洖if(obj===null)returnobjif(cache.get(obj))returncache.get(obj)//闃叉寰幆寮曠敤锛岀▼搴忚繘鍏ユ寰幆if(objinstanceofDate)returnnewDate(obj)if(objinstanceofRegExp)returnnewRegExp(obj)//鎵惧埌鍘熷瀷鏋勯€犲嚱鏁帮紝鍘熷瀷涓婄殑鏋勯€犲嚱鏁版寚鍚戝綋鍓嶅墠涓€涓璞$殑鏋勯€犲嚱鏁發etcloneObj=newobj.constructor()cache.set(obj,cloneObj)//缂撳瓨澶嶅埗鐨勫璞℃潵澶勭悊寰幆寮曠敤for(letkeyinobj){if(obj.hasOwnProperty(key)){cloneObj[key]=deepClone(obj[key],cache)//閫掑綊澶嶅埗}}returncloneObj}//testconstobj={name:'Jack',address:{x:100,y:200}}obj.a=obj//寰幆寮曠敤constnewObj=deepClone(obj)console.log(newObj.address===obj.address)//falsecopycode4,implementPromiseclassMyPromise{constructor(executor){//executorthis.status='pending'//绛夊緟鐘舵€乼his.value=null//鎴愬姛鎴栧け璐ュ弬鏁皌his.fulfilledCallbacks=[]//鎴愬姛鍑芥暟闃熷垪this.rejectedCallbacks=[]//澶辫触鍑芥暟闃熷垪constthat=thisfunctionresolve(value){//鎴愬姛鏂规硶if(that.status==='pending'){that.status='resolved'that.value=valuethat.fulfilledCallbacks.forEach(myFn=>myFn(that.value))//鎵ц鍥炶皟鏂规硶}}鍑芥暟nreject(value){//澶辫触鏂规硶if(that.status==='pending'){that.status='rejected'that.value=valuethat.rejectedCallbacks.forEach(myFn=>myFn(that.value))//鎵ц鍥炶皟鏂规硶}}try{executor(resolve,reject)}catch(err){reject(err)}}then(onFulfilled,onRejected){if(this.status==='pending'){//绛夊緟鐘舵€侊紝鍚戞垚鍔熷嚱鏁伴槦鍒楁坊鍔犲洖璋冨嚱鏁皌his.fulfilledCallbacks.push(()=>{onFulfilled(this.value)})//绛夊緟鐘舵€侊紝鍚戞垚鍔熷嚱鏁伴槦鍒楁坊鍔犲洖璋冨嚱鏁癴ailedfunctionQueuethis.rejectedCallbacks.push(()=>{onRejected(this.value)})}if(this.status==='resolved'){//鏀寔鍚屾璋冪敤console.log('this',this)onFulfilled(this.value)}if(this.status==='rejected'){//鏀寔鍚屾璋冪敤onRejected(this.value)}}}//娴嬭瘯鍑芥暟fn(){returnnewMyPromise((resolve,reject)=>{setTimeout(()=>{if(Math.random()>0.6){resolve(1)}else{reject(2)}},1000)})}fn().then(res=>{console.log('res',res)//res1},err=>{console.log('err',err)//err2})澶嶅埗浠g爜5銆佸紓姝ユ帶鍒跺苟鍙戝嚱鏁發imitRequest(urls=[],limit=3){returnnewPromise((resolve,reject)=>{constlen=urls.lengthletcount=0//褰撳墠浠诲姟鏁癱onststart=async()=>{consturl=urls.shift()//浠庢暟缁勪腑鑾峰彇绗竴涓换鍔f(url){try{awaitaxios.post(url)if(count==len-1){//鏈€鍚庝竴涓换鍔℃垚鍔焤esolve()}else{count++//鎴愬姛锛屽紑濮嬩笅涓€涓换鍔tart()}}catch(e){if(count==len-1){//鏈€鍚庝竴涓换鍔″け璐esolve()}else{count++//澶辫触锛屽紑濮嬩笅涓€涓换鍔tart()}}}//寮€濮嬮檺鍒朵换鍔hile(limit>0){start()limit-=1}})}//娴嬭瘯limitRequest(['http://xxa','http://xxb','http://xxc','http://xxd','http://xxe'])澶嶅埗浠g爜6銆丒S5缁ф壙锛堝瘎鐢熺粍鍚堢户鎵匡級鍑芥暟Parent(name){this.name=name}Parent.prototype.eat=function(){console.log(this.name+'iseating')}functionChild(name,age){Parent.call(this,name)this.age=age}Child.prototype=Object.create(Parent.prototype)Child.prototype.contructor=ChildChild.prototype.study=function(){console.log(this.name+'isstudying')}//娴嬭瘯璁╁瀛?newChild('灏忔晱g',16)console.log(child.name)//xiaomingchild.eat()//xiaomingiseatingchild.study()//xiaomingiseatingchild.study()//xiaomingiseatingchild.study()//xiaomingiseatingchild.study()//xiaomingiseatingchild.study()//xiaomingsortsortsort//瀵规暟瀛楄繘琛屾帓搴忥紝缂╁啓constarr=[3,2,4,1,5]arr.sort((a,b)=>a-b)console.log(arr)//[1,2,3,4,5]//鎺掑簭瀛楁瘝锛岄€熻constarr=['b','c','a','e','d']arr.sort()console.log(arr)//['a','b','c','d','e']澶嶅埗浠g爜鍐掓场鎺掑簭鍑芥暟bubbleSort(arr){letlen=arr.lengthfor(leti=0;iarr[j+1]){letnum=arr[j]arr[j]=arr[j+1]arr[j+1]=num}}//姣忔閬嶅巻缁撴潫锛屽彲浠ユ壘鍒颁竴涓渶澶у€兼斁鍦ㄦ暟缁勭殑鏈熬}returnarr}//testconsole.log(bubbleSort([2,3,1,5,4]))//[1,2,3,4,5]澶嶅埗浠g爜8锛屾暟缁勫幓閲嶈缃幓閲峜osntnewArr=[...newSet(arr)]澶嶅埗浠g爜鏁扮粍銆傛潵鑷噸澶嶆暟鎹垹闄onstnewArr=Array.from(newSet(arr))澶嶅埗浠g爜indexOf閲嶅鏁版嵁鍒犻櫎鍑芥暟resetArr(arr){letres=[]arr.forEach(item=>{if(res.indexOf(item)===-1){res.push(item)}})returnres}//娴嬭瘯constarr=[1,1,2,3,3]console.log(resetArr(arr))//[1,2,3]澶嶅埗浠g爜9锛岃幏鍙杣rl鍙傛暟URLSearchParamsmethod//鍒涘缓涓€涓猆RLSearchParams瀹炰緥consturlSearchParams=newURLSearchParams(window.location.search);//灏嗛敭鍊煎鍒楄〃杞崲涓哄璞onstparams=Object.fromEntries(urlSearchParams.entries());澶嶅埗浠g爜鎷嗗垎鏂规硶functiongetParams(url){constres={}if(url.includes('?')){conststr=url.split('?')[1]constarr=str.split('&')arr.forEach(item=>{constkey=item.split('=')[0]constval=item.split('=')[1]res[key]=decodeURIComponent(val)//瑙g爜})}returnres}//testconstuser=getParams('http://www.baidu.com?user=%E9...')console.log(user)//{user:'闃块',age:'16'}澶嶅埗浠g爜10锛屼簨浠舵€荤嚎|鍙戝竷璁㈤槄妯″紡classEventEmitter{constructor(){this.cache={}}on(name,fn){if(this.cache[name]){this.cache[name].push(fn)}else{this.cache[name]]=[fn]}}off(name,fn){consttasks=this.cache[name]if(tasks){constindex=tasks.findIndex((f)=>f===fn||f.callback===fn)if(index>=0){tasks.splice(index,1)}}}emit(name,once=false){if(this.cache[name]){//鍒涘缓涓€涓壇鏈紝濡傛灉鍥炶皟鍑芥暟缁х画娉ㄥ唽鐩稿悓鐨勪簨浠讹紝灏嗗鑷存棤闄愬惊鐜痗onsttasks=this.cache[name].slice()for(letfnoftasks){fn();}if(once){deletethis.cache[name]}}}}//娴嬭瘯consteventBus=newEventEmitter()consttask1=()=>{console.log('task1');}consttask2=()=>{console.log('task2');}eventBus.on('task',task1)eventBus.on('task',task2)eventBus.off('task',task1)setTimeout(()=>{eventBus.emit('task')//task2},1000)澶嶅埗涓婇潰鐨勪唬鐮佹槸宸ヤ綔鎴栨眰鑱屼腑鏈€甯哥敤鐨勬墜鍐欏姛鑳戒綘閮芥帉鎻′簡鍚楋紵娆㈣繋鍦ㄨ瘎璁哄尯浜ゆ祦銆傚鏋滄枃绔犲浣犳湁甯姪锛屽埆蹇樹簡缁欎釜鏈変环鍊肩殑璧炲摝锛佸惉璇村枩娆㈢殑浜鸿繍姘旈兘涓嶄細宸€傜浉淇℃潵骞翠綘浼氭槸绗竴涓崌鑱屽姞钖殑浜簙馃槂鏈€鍚庯紝濡傛灉浣犺寰楄繖绡囨枃绔犲浣犳湁甯姪锛岃鐐逛釜璧炪€傛垨鑰呭彲浠ュ姞鍏ユ垜鐨勫紑鍙戜氦娴佺兢锛?025263163浜掔浉瀛︿範锛屾垜浠細鏈変笓涓氱殑鎶€鏈В绛斻€傚鏋滄偍瑙夊緱杩欑瘒鏂囩珷瀵规偍鏈夌敤锛岃缁欐垜浠殑寮€婧愰」鐩竴涓皬鏄熸槦锛歨ttps://gitee銆俢om/ZhongBangKe...闈炲父鎰熻阿锛?/p>