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

36个工作中常用的JavaScript函数片段

时间:2023-04-05 20:34:40 HTML5

濡傛灉鏂囩珷鍜岀瑪璁拌兘缁欎綘甯︽潵涓€鐐瑰府鍔╂垨鍚彂锛岃涓嶈鍚濆暚浣犵殑鐐硅禐鍜屾敹钘忥紝浣犵殑涓€瀹氭槸鎴戝墠杩涚殑鏈€澶у姩鍔涴煒侀檮涓婄瑪璁伴摼鎺ワ紝闃呰鏇村寰€鏈熶紭璐ㄦ枃绔爄ssues锛屽彲浠ョЩ姝ユ煡鐪嬶紝鍠滄鐨勮瘽鍙互缁欐垜鐐硅禐鍜岄紦鍔憋細https://github.com/Wscats/CV/issues/32ArrayArrayArraydeduplicationfunctionnoRepeat(arr){return[...newSet(arr)];}姹傛暟缁勬渶澶у嚱鏁癮rrayMax(arr){returnMath.max(...arr);}姹傛暟缁勬渶灏忓嚱鏁癮rrayMin(arr){returnMath.min(...arr);}杩斿洖鍘熸暟缁勫嚱鏁伴櫎浠ize浣滀负鏁扮粍鐨勯暱搴hunk(arr,size=1){returnArray.from({length:Math.ceil(arr.length/size),},(v,i)=>arr.slice(i*size,i*size+size));}妫€鏌ユ暟缁勪腑鏌愪釜鍏冪礌鐨勫嚭鐜癴unctioncountOccurrences(arr,value){returnarr.reduce((a,v)=>(v===value?a+1:a+0),0);}灞曞钩鏁扮粍鐨勯粯璁ゆ繁搴︽槸瀹屽叏灞曞紑functionflatten(arr,depth=-1){if(depth===-1){return[].concat(...arr.map((v)=>(Array.isArray(v)?this.flatten(v):v)));}if(depth===1){returnarr.reduce((a,v)=>a.concat(v),[]);}returnarr.reduce((a,v)=>a.concat(Array.isArray(v)?this.flatten(v,depth-1):v),[]);}姣旇緝涓や釜鏁板垎缁勫苟杩斿洖涓嶅悓鐨勫厓绱爁unctiondiffrence(arrA,arrB){returnarrA.filter((v)=>!arrB.includes(v));}杩斿洖涓や釜鏁扮粍涓浉鍚岀殑鍏冪礌functionintersection(arr1,arr2){returnarr2.filter((v)=>arr1.includes(v));}浠庡彸渚хЩ闄涓厓绱爁unctiondropRight(arr,n=0){returnni%nth===nth-1);}杩斿洖鏁扮粍涓殑绗琻涓厓绱犳敮鎸佽礋鏁扮殑鏁扮粍functionnthElement(arr,n=0){return(n>=0?arr.slice(n,n+1):arr.slice(n))[0];}杩斿洖鏁扮粍澶村厓绱爁unctionhead(arr){returnarr[0];}returnarrayendelementfunctionlast(arr){returnarr[arr.length-1];}arrayshufflefunctionshuffle(arr){letarray=arr;璁╃储寮?鏁扮粍銆傞暱搴?while(index){绱㈠紩-=1;璁﹔andomInedx=Math.鍦版澘锛堟暟瀛︺€傞殢鏈猴紙锛?绱㈠紩锛夛紱璁╀腑闂翠欢=鏁扮粍[绱㈠紩]锛涙暟缁刐绱㈠紩]=鏁扮粍[randomInedx];array[randomInedx]=涓棿浠讹紱}returnarray;}娴忚鍣ㄥ璞OM鍒ゆ柇娴忚鍣ㄦ槸鍚︽敮鎸丆SS灞炴€?***鍛婄煡娴忚鍣ㄦ敮鎸佺殑鎸囧畾CSS灞炴€?@param{String}key-CSS灞炴€э紝涓哄睘鎬у悕锛屼笉闇€瑕佹坊鍔犲墠缂€*@returns{String}-鏀寔鐨勫睘鎬ф潯浠?/functionvalidateCssKey(key){constjsKey=toCamelCase(key);//涓€浜沜ss灞炴€х敱杩炲瓧绗︾粍鎴恑f(jsKeyindocument.documentElement.style){returnkey;}璁﹙alidKey="";//灞炴€у悕鍦╦s涓槸鍓嶇紑褰㈠紡锛屽睘鎬у€煎湪css涓槸鍓嶇紑褰㈠紡//缁忚繃灏濊瘯锛學ebkit涔熷彲浠ユ槸灏忓啓棣栧瓧姣峸ebkitconstprefixMap={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-",};for(constjsPrefixinprefixMap){conststyleKey=toCamelCase(`${jsPrefix}-${jsKey}`);if(styleKeyindocument.documentElement.style){validKey=prefixMap[jsPrefix]+key;浼戞伅;}}returnvalidKey;}/***Hyphenated灏嗛┘宄板紡瀛楃涓茶浆鎹负椹煎嘲寮?/functiontoCamelCase(value){returnvalue.replace(/-(\w)/g,(matched,letter)=>{returnletter.toUpperCase();});}/***妫€鏌ユ祻瑙堝櫒鏄惁鏀寔鏌愪釜css灞炴€у€硷紙es6鐗堟湰锛?@param{String}key-瑕佹鏌ョ殑灞炴€ц鍊兼墍灞炵殑css灞炴€х殑鍚嶇О*@param{String}value-瑕佹鏌ョ殑css灞炴€х殑鍊硷紙涓嶅甫鍓嶇紑锛?@returns{String}-杩斿洖娴忚鍣ㄦ敮鎸佺殑灞炴€у€?/functionvaliateCssValue(key,value){constprefix=["-o-","-ms-","-moz-","-w鈥嬧€媏bkit-",""];constprefixValue=鍓嶇紑銆傚湴鍥撅紙锛堥」鐩級=>{杩斿洖椤圭洰+浠峰€?}锛?constelement=document.createElement("div");甯搁噺eleStyle=element.style;//鍦ㄥ簲鐢ㄦ瘡涓墠缂€鐨勬儏鍐典笅锛屾渶鍚庡簲璇ヤ笉搴旂敤浠讳綍鍓嶇紑锛屽叿浣撳彇鍐充簬鍝釜娴忚鍣ㄧ敓鏁堟儏鍐?/杩欓噷鏄墠缂€涓渶鍚庝竴涓厓绱犳渶濂芥槸''prefixValue.forEach((item)=>{eleStyle[key]=item;});returneleStyle[key];}/***妫€鏌ユ祻瑙堝櫒鏄惁鏀寔鏌愪釜css灞炴€у€?@param{String}key-瑕佹鏌ョ殑灞炴€у€肩殑css灞炴€у悕*@param{String}value-瑕佹鏌ョ殑css灞炴€у€硷紙涓嶅甫鍓嶇紑锛?@returns{String}-杩斿洖娴忚鍣ㄦ敮鎸佺殑灞炴€у€?/functionvaliateCssValue(key,value){varprefix=["-o-","-ms-","-moz-","-w鈥嬧€媏bkit-",""];varprefixValue=[];for(vari=0;i((a[v.slice(0,v.indexOf("="))]=v.slice(v.indexOf("=")+1)),a),{});}椤甸潰璺宠浆锛屾槸鍚﹁褰曞巻鍙瞗unctionredirect(url,asLink=true){asLink?(window.location.href=url):window.location.replace(url);}婊氬姩鏉″洖鍒伴《閮ㄥ姩鐢诲嚱鏁皊crollToTop(){constscrollTop=document.documentElement.scrollTop||鏂囨。.body.scrollTop;濡傛灉(scrollTop>0){window.requestAnimationFrame(scrollToTop);window.scrollTo(0,c-c/8);}else{window.cancelAnimationFrame(scrollToTop);}}澶嶅埗鏂囨。functioncopy(str){constel=document.createElement("textarea");el.value=str;el.setAttribute("鍙","");el.style.position="缁濆";el.style.left="-9999px";el.style.top="-9999px";鏂囨。.body.appendChild(el);constselected=document.getSelection().rangeCount>0?鏂囨。.getSelection().getRangeAt(0):false;el.select();document.execCommand("澶嶅埗");鏂囨。.body.removeChild(el);濡傛灉锛堥€変腑锛墈document.getSelection().removeAllRanges();document.getSelection().addRange(閫変腑);}}妫€娴嬭澶囩被鍨媐unctiondetectDeviceType(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)?"Mobile":"Desktop";}Cookie澧炲姞涔愯叮actionsetCookie(key,value,expiredays){varexdate=newDate();exdate.setDate(exdate.getDate()+expiredays);document.cookie=key+"="+escape(value)+(expiredays==null?"":";expires="+exdate.toGMTString());}鍒犻櫎鍑芥暟delCookie(name){varexp=newDate();exp.setTime(exp.getTime()-1);varcval=getCookie(鍚嶇О);if(cval!=null){document.cookie=name+"="+cval+";expires="+exp.toGMTString();}}妫€鏌ュ嚱鏁癵etCookie(name){vararr,reg=newRegExp("(^|)"+name+"=([^;]*)(;|$)");濡傛灉((arr=document.cookie.match(reg))){杩斿洖arr[2];}else{杩斿洖绌哄€硷紱}}鏃ユ湡鏃堕棿鎴宠浆鎹负鏃堕棿銆傞粯璁や负褰撳墠鏃堕棿銆傝浆鎹㈢粨鏋渋sMs鏄椂闂存埑鏄惁涓烘绉抐unctiontimestampToTime(timestamp=Date.parse(newDate()),isMs=true){constdate=newDate(timestamp*(isMs?1:1000));杩斿洖`${鏃ユ湡銆俫etFullYear()}-${鏃ユ湡銆俫etMonth()+1<10?"0"+(date.getMonth()+1):date.getMonth()+1}-${date.getDate()}${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;}Document瀵硅薄DOM鍥哄畾婊氬姩鏉?***鍔熻兘璇存槑锛氫竴浜涗笟鍔″満鏅紝姣斿鍑虹幇寮规鏃讹紝闇€瑕佺姝㈤〉闈㈡粴鍔紝杩欐槸涓€涓吋瀹笰ndroid鍜宨OS鐨勭姝㈤〉闈㈡粴鍔ㄧ殑鏂规*/letscrollTop=0;functionpreventScroll(){//瀛樺偍褰撳墠婊氬姩浣嶇疆scrollTop=window.scrollY;//鍥哄畾鍙粴鍔ㄥ尯鍩燂紝鍙粴鍔ㄥ尯鍩熼珮搴︿负0鍚庝笉鑳芥粴鍔╠ocument.body.style["overflow-y"]="hidden";document.body.style.position="鍥哄畾";document.body.style.width="100%";document.body.style.top=-scrollTop+"px";//document.body.style['overscroll-behavior']='none'}functionrecoverScroll(){document.body.style["overflow-y"]="auto";document.body.style.position="static";//document.querySelector('body').style['overscroll-behavior']='none'window.scrollTo(0,scrollTop);}鍒ゆ柇褰撳墠浣嶇疆鏄惁鍦ㄩ〉闈㈠簳閮ㄨ繑鍥炲€糹strue/falsefunctionbottomVisible(){return(document.documentElement.clientHeight+window.scrollY>=(document.documentElement.scrollHeight||document.documentElement.clientHeight));}鍒ゆ柇鍏冪礌鍦╲iew鑼冨洿鍐呮槸鍚﹀彲瑙丳artiallyVisible鏄惁鏄畬鍏ㄥ彲瑙佺殑鍑芥暟elementIsVisibleInViewport(el,partiallyVisible=false){const{椤堕儴銆佸乏渚с€佸簳閮ㄣ€佸彸渚=el.getBoundingClientRect();杩斿洖閮ㄥ垎鍙锛?(top>0&&top0&&bottom0&&left0&&right=0&&left>=0&&bottom<=innerHeight&&right<=innerWidth;}鑾峰彇鍏冪礌css鏍峰紡functiongetStyle(el,ruleName){returngetComputedStyle(el,null).getPropertyValue(ruleName);}杩涘叆鍏ㄥ睆functionlaunchFullscreen(element){濡傛灉(element.requestFullscreen){element.requestFullscreen();}elseif(element.mozRequestFullScreen){element.mozRequestFullScreen();}elseif(element.msRequestFullscreen){element.msRequestFullscreen();}elseif(element.webkitRequestFullscreen){element.webkitRequestFullScreen();}}launchFullscreen(document.documentElement);launchFullscreen(document.getElementById("id"));//鏌愪釜鍏冪礌杩涘叆鍏ㄥ睆鍜岄€€鍑哄叏灞廸unctionexitFullscreen(){if(document.exitFullscreen){document.exitFullscreen();}elseif(document.msExitFullscreen){document.msExitFullscreen();}elseif(document.mozCancelFullScreen){document.mozCancelFullScreen();}elseif(document.webkitExitFullscreen){document.webkitExitFullscreen();}}exit;Fullscreenevent(doc).addEventListener("fullscreenchange",function(e){if(document.fullscreenElement){console.log("杩涘叆鍏ㄥ睆");}else{console.log("閫€鍑哄叏灞?);}});鍒嗕綅鏁板垎鍓插嚱鏁癱ommafy(num){returnnum.toString().indexOf(".")!==-1?num.toLocaleString():num.toString().replace(/(\d)(?=(?:\d{3})+$)/g,"$1,");}鐢熸垚闅忔満鏁板嚱鏁皉andomNum(min,max){switch(arguments.length){妗堜緥1:returnparseInt(Math.random()*min+1,10);鎯呭喌2锛氳繑鍥瀙arseInt(Math.random()*(max-min+1)+鍒嗛挓,10);榛樿鍊硷細杩斿洖0锛泒}浜ゆ祦鏂囩珷鍚屾鎸佺画鏇存柊銆傛偍鍙互鍦ㄥ井淇℃悳绱⑩€滃墠绔瑙堚€濓紝鍏虫敞鍏紬鍙凤紝鏂逛究浣跨敤銆備箣鍓嶇殑鏂囩珷鏀跺綍鍦╤ttps://github.com/Wscats/art...娆㈣繋澶у鍏虫敞浜ゆ祦馃榿