当前位置: 首页 > Web前端 > HTML

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

时间:2023-03-28 00:18:24 HTML

楂樻ゼ鎷斿湴鑰岃捣锛屽湴鍩虹墷鍥猴紝鏂硅兘绔嬩簬涓嶈触涔嬪湴銆備粖澶╃粰澶у甯︽潵鐨勬槸10涓父鐢ㄧ殑JavaScript鎵嬪啓鍑芥暟锛岄噸瑕佺殑鍦版柟閮藉姞浜嗘敞閲娿€傛湁浜涙槸浠庡埆浜洪偅閲屽€熸潵鐨勶紝鏈変簺鏄嚜宸卞啓鐨勩€傚鏋滄湁涓嶅噯纭殑鍦版柟锛岃鎸囨銆?.闃叉姈鍔熻兘debounce(fn,delay){lettimerreturnfunction(...args){if(timer){clearTimeout(timer)}timer=setTimeout(()=>{fn.apply(this,args)},delay)}}//娴嬭瘯鍑芥暟task(){console.log('runtask')}constdebounceTask=debounce(task,1000)window.addEventListener('scroll',debounceTask)2.鑺傛祦鍑芥暟throttle(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)3.娣辨嫹璐濆嚱鏁癲eepClone(obj,cache=newWeakMap()){if(typeofobj!=='object')returnobj//鏅€氱被鍨嬶紝鐩存帴杩斿洖if(obj===null)returnobjif(cache.get(obj))returncache.get(obj)//闃叉寰幆寮曠敤锛岀▼搴忚繘鍏ユ寰幆if(objinstanceofDate)returnnewDate(obj)if(objinstanceofRegExp)returnnewR渚嬪Exp(obj)//鎵惧埌鍘熷瀷涓婄殑鏋勯€犲嚱鏁帮紝鍘熷瀷涓婄殑鏋勯€犲嚱鏁版寚鍚戝綋鍓嶅璞$殑鏋勯€犲嚱鏁發etcloneObj=newobj.constructor()cache.set(obj,cloneObj)//缂撳瓨澶嶅埗鐨勫璞″鐞嗗惊鐜紩鐢╟asefor(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)//false4銆両mplementPromiseclassMyPromise{constructor(executor){//鎵ц鍣╡xecutorthis.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))//鎵ц鍥炶皟鏂规硶}}functionreject(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)})//绛夊緟鐘舵€侊紝灏嗗洖璋冨嚱鏁板姞鍏ュけ璐ュ嚱鏁伴槦鍒梩his.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})5.寮傛鎺у埗骞跺彂鍑芥暟limitRequest(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'])6銆丒S5缁ф壙锛堝瘎鐢熺粍鍚堢户鎵縤nherit)functionParent(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+'姝e湪瀛︿範')}//testletchild=newChild('xiaoming',16)console.log(child.name)//xiaomingchild.eat()//xiaomingiseatingchild.study()//xiaomingisstudying7,鏁扮粍鎺掑簭Sorting//瀵规暟瀛楄繘琛屾帓搴忥紝绠€鍐檆onstarr=[3,2,4,1,5]arr.sort((a,b)=>a-b)console.log(arr)//[1,2,3,4,5]//瀛楁瘝鎺掑簭锛岀畝鍐檆onstarr=['b','c','a','e','d']arr.sort()console.log(arr)//['a','b','c','d','e']鍐掓场鎺掑簭鍑芥暟bubbleSort(arr){letlen=arr.lengthfor(leti=0;iarr[j+1]){璁﹏um=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]8.鏁扮粍鍘婚噸璁剧疆鍘婚噸cosntnewArr=[...newSet(arr)]Array.fromdeduplicationconstnewArr=Array.from(newSet(arr))indexOfdeduplicationfunctionresetArr(arr){letres=[]arr.forEach(item=>{if(res.indexOf(item)==澶嶅埗浠g爜=-1){res.push(item)}})returnres}//娴嬭瘯甯搁噺arr=[1,1,2,3,3]console.log(resetArr(arr))//[1,2,3]9銆傝幏鍙杣rl鍙傛暟URLSearchParams鏂规硶//鍒涘缓涓€涓猆RLSearchParams瀹炰緥consturlSearchParams=newURLSearchParams(window.location.search);//灏嗛敭鍊煎鍒楄〃杞崲涓哄璞onstparams=Object.fromEntries(urlSearchParams.entries());鎷嗗垎鏂规硶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%98%BF%E9%A3%9E&age=16')console.log(user)//{user:'闃块',age:'16'}10.浜嬩欢鎬荤嚎|鍙戝竷-璁㈤槄妯″紡.cache[name]=[fn]}}off(name,fn){consttasks=this.cache[name]if(tasks){constindex=tasks.findIndex((f)=>f===fn||f.callback===fn)if(index>=0){浠诲姟銆俿plice(index,1)}}}emit(name,once=false){if(this.cache[name]){//鍒涘缓涓€涓壇鏈紝濡傛灉鍥炶皟鍑芥暟缁х画娉ㄥ唽鍚屼竴涓簨浠讹紝浼氶€犳垚鏃犻檺loopconsttasks=this.cache[name].slice()for(letfnoftasks){fn();}if(once){deletethis.cache[name]}}}}//娴嬭瘯consteventBus=newEventEmitter()consttask1=()=>{console.log('task1');}consttask2=()=>{console.log('task2');}鍓嶅ntBus.on('task',task1)eventBus.on('task',task2)eventBus.off('task',task1)setTimeout(()=>{eventBus.emit('task')//task2},1000锛変互涓婃槸宸ヤ綔鎴栨眰鑱屼腑鏈€甯哥敤鐨勬墜鍐欏姛鑳姐€備綘閮芥帉鎻′簡鍚楋紵娆㈣繋鍦ㄨ瘎璁哄尯浜ゆ祦銆傚鏋滄枃绔犲鎮ㄦ湁甯姪锛屽埆蹇樹簡缁欎釜鏈変环鍊肩殑璧炲摝锛佸惉璇村枩娆㈢殑浜鸿繍姘旈兘涓嶄細宸紝鐩镐俊鏉ュ勾浣犱細鏄涓€涓崌鑱屽姞钖殑~馃槂