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

20个简单实用的JavaScript技巧

时间:2023-03-26 22:07:52 JavaScript

1銆傛粴鍔ㄥ埌椤甸潰椤堕儴鎴戜滑鍙互浣跨敤window.scrollTo()鏉ュ钩婊戝湴婊氬姩鍒伴〉闈㈤《閮ㄣ€俢onstscrollToTop=()=>{window.scrollTo({top:0,left:0,behavior:"smooth"});};2.婊氬姩鍒伴〉闈㈠簳閮ㄥ綋鐒讹紝濡傛灉浣犵煡閬撻〉闈㈢殑楂樺害锛屼綘涔熷彲浠ュ钩婊戝湴婊氬姩鍒伴〉闈㈠簳閮ㄣ€俢onstscrollToBottom=()=>{window.scrollTo({top:document.documentElement.offsetHeight,left:0,behavior:"smooth",});};3.灏嗗厓绱犳粴鍔ㄥ埌鍙鍖哄煙鏈夋椂鎴戜滑闇€瑕佸皢鍏冪礌婊氬姩鍒板彲瑙佸尯鍩燂紝鎬庝箞鍔烇紵浣跨敤scrollIntoView灏辫冻澶熶簡銆俢onstsmoothScroll=(element)=>{element.scrollIntoView({behavior:"smooth",});};4.鍏ㄥ睆鏄剧ず鍏冪礌浣犱竴瀹氶亣鍒拌繃杩欐牱鐨勫満鏅紝浣犻渶瑕佸叏灞忔挱鏀捐棰戯紝骞跺湪娴忚鍣ㄤ腑鍏ㄥ睆鎵撳紑椤甸潰銆傚父閲廹oToFullScreen=(鍏冪礌)=>{鍏冪礌=鍏冪礌||鏂囦欢涓讳綋锛涘鏋?element.requestFullscreen){element.requestFullscreen();}elseif(element.mozRequestFullScreen){element.mozRequestFullScreen();}elseif(element.msRequestFullscreen){element.msRequestFullscreen();}elseif(element.webkitRequestFullscreen){element.webkitRequestFullScreen();}};5.閫€鍑烘祻瑙堝櫒鍏ㄥ睆鐘舵€佹槸鐨勶紝杩欎釜鏄拰绗?鐐逛竴璧蜂娇鐢ㄧ殑锛屼綘涔熶細鏈夐€€鍑烘祻瑙堝櫒鍏ㄥ睆鐘舵€佺殑鍦烘櫙銆俢onstgoExitFullscreen=()=>{if(document.exitFullscreen){document.exitFullscreen();}elseif(document.msExitFullscreen){document.msExitFullscreen();}elseif(document.mozCancelFullScreen){document.mozCancel)FullScreen(;}elseif(document.webkitExitFullscreen){document.webkitExitFullscreen();}};6.鑾峰彇鏁版嵁绫诲瀷濡備綍閫氳繃鑾峰彇鍙橀噺鐨勬暟鎹被鍨嬪嚱鏁?constgetType=(value)=>{constmatch=Object.prototype.toString.call(value).match(/(\w+)]/)returnmatch[1].toLocaleLowerCase()}getType()//undefinedgetType({}})//objectgetType([])//arraygetType(1)//numbergetType('fatfish')//stringgetType(true)//booleangetType(/fatfish/)//regexp7.鍋滄鍐掓场浜嬩欢鏄€傜敤浜庢墍鏈夊钩鍙伴槻姝簨浠跺啋娉$殑鏂规硶銆俢onststopPropagation=(event)=>{event=event||绐楀彛浜嬩欢锛涘鏋?event.stopPropagation){event.stopPropagation();}else{event.cancelBubble=true;}};娣辨嫹璐濅竴涓璞″浣曟繁搴︽嫹璐濆祵濂楀璞★紵constdeepCopy=(obj,hash=newWeakMap())=>{if(objinstanceofDate){returnnewDate(obj);}if(objinstanceofRegExp){returnnewRegExp(obj);}if(hash.has(obj)){returnhash.get(obj);}璁゛llDesc=Object.getOwnPropertyDescriptors(obj);璁ヽloneObj=Object.create(Object.getPrototypeOf(obj),allDesc);hash.set(obj,cloneObj);for(letkeyofReflect.ownKeys(obj)){if(obj[key]&&typeofobj[key]==="object"){cloneObj[key]=deepCopy(obj[key],hash);}else{cloneObj[key]=obj[key];}}杩斿洖cloneObj;};纭畾璁惧绫诲瀷鎴戜滑缁忓父蹇呴』杩欐牱鍋氭墠鑳藉湪鎵嬫満涓婃樉绀篈閫昏緫锛屽湪PC涓婃樉绀築閫昏緫銆傚熀鏈笂锛岃澶囩被鍨嬫槸閫氳繃璇嗗埆娴忚鍣ㄧ殑userAgent鏉ョ‘瀹氱殑銆俢onstisMobile=()=>{return!!navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|WindowsPhone|Phone)/i);};10.鍒ゆ柇璁惧鏄疉ndroid杩樻槸IOS闄や簡瑕佸尯鍒嗘槸绉诲姩绔繕鏄疨C绔紝鎴戜滑缁忓父闇€瑕佸尯鍒嗗綋鍓嶈澶囨槸Android杩樻槸IOS銆俢onstisAndroid=()=>{return/android/i.test(navigator.userAgent.toLowerCase());};constisIOS=()=>{letreg=/iPhone|iPad|iPod|iOS|Macintosh/i;杩斿洖reg.test(navigator.userAgent.toLowerCase());};11.鑾峰彇娴忚鍣ㄧ被鍨嬪強鐗堟湰浣滀负鍓嶇寮€鍙戣€咃紝浣犲彲鑳戒細閬囧埌鍚勭鍏煎鎬ч棶棰橈紝浣犲彲鑳介渶瑕佽幏鍙栨祻瑙堝櫒鐨勭被鍨嬪強鐗堟湰銆俢onstgetExplorerInfo=()=>{璁﹖=navigator.userAgent.toLowerCase();杩斿洖0<=t.indexOf("msie")锛焮//ie<11type:"IE",version:Number(t.match(/msie([\d]+)/)[1]),}:!!t.match(/trident\/.+?rv:(([\d.]+)))/)锛焮//鍗?1绫诲瀷锛氣€淚E鈥濓紝鐗堟湰锛?1锛寎锛?<=t.indexOf锛堚€渆dge鈥濓級锛焮type:"Edge",version:Number(t.match(/edge\/([\d]+)/)[1]),}:0<=t.indexOf("firefox")锛焮绫诲瀷锛氣€淔irefox鈥濓紝鐗堟湰锛歂umber(t.match(/firefox\/([\d]+)/)[1])锛寎锛?<=t.indexOf锛堚€渃hrome鈥濓級锛焮type:"Chrome",version:Number(t.match(/chrome\/([\d]+)/)[1]),}:0<=t.indexOf("opera")锛焮绫诲瀷锛氣€淥pera鈥濓紝鐗堟湰锛歂umber(t.match(/opera.([\d]+)/)[1]),}:0<=t.indexOf("Safari")?{type:"Safari",version:Number(t.match(/version\/([\d]+)/)[1]),}:{type:t,version:-1,};};12.setcookiescookie鍙兘鏄垜瑙佽繃鏈€鐑傜殑API锛屽お闅剧敤浜嗭紝涓嶅緱涓嶉噸鏂板皝瑁咃紝鏈€澶ч檺搴︽彁楂樺紑鍙戞晥鐜嘽onstsetCookie=(key,value,expire)=>{constd=newDate();d.setDate(d.getDate()+expire);document.cookie=`${key}=${value};expires=${d.toUTCString()}`;};闄や簡鍐檆ookie锛屾垜浠繕浼氬弬涓庡畠鐨勮鎿嶄綔constgetCookie=(key)=>{constcookieStr=unescape(document.cookie);constarr=cookieStr.split(";");letcookieValue="";for(leti=0;i{document.cookie=`${encodeURIComponent(key)}=;expires=${newDate()}`;};15.鐢熸垚涓€涓殢鏈哄瓧绗︿覆銆備笉鐭ラ亾澶у鏈夋病鏈夐亣鍒拌繃闇€瑕佺敓鎴愰殢鏈哄瓧绗︿覆鐨勫満鏅€傞亣鍒拌繃寰堝娆′簡锛屾瘡娆¢兘瑕乬oogle涓€涓嬶紝鐩村埌瀛︿細杩欎釜宸ュ叿鐨勫姛鑳姐€俢onstrandomString=(len)=>{letchars="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";璁﹕trLen=chars.length;璁﹔andomStr="";for(leti=0;i{returnstr.charAt(0).toUpperCase()+str.slice(1);};fistLetterUpper('fatfish')//Fatfish17銆傜敓鎴愭寚瀹氳寖鍥村唴鐨勯殢鏈烘暟鍙兘鍑轰簬娴嬭瘯鐩殑锛屾垜缁忓父闇€瑕佺敓鎴愭煇涓寖鍥村唴鐨勯殢鏈烘暟銆俢onstrandomNum=(min,max)=>Math.floor(Math.random()*(max-min+1))+min;randomNum(1,10)//6randomNum(10,20)//1118.鍛戒腑shuffletheorderofarray鎬庝箞鎵撲贡鏁扮粍鍘熸潵鐨勯『搴忥紵constshuffleArray=(array)=>{returnarray.sort(()=>0.5-Math.random())}letarr=[1,-1,10,5]shuffleArray(arr)//[5,-1,10,1]shuffleArray(arr)//[1,10,-1,5]浠庢暟缁勪腑鑾峰彇闅忔満鍊煎湪鍋氫竴涓僵绁ㄩ」鐩箣鍓嶏紝闇€瑕佽鏁扮粍涓殑濂栧搧闅忔満鍑虹幇銆俢onstgetRandomValue=array=>array[Math.floor(Math.random()*array.length)];constprizes=['$100','馃崼','馃崝']getRandomValue(prizes)//馃崼getRandomValue(prizes)//馃崝getRandomValue(prizes)//馃崼鏍煎紡鍖栬揣甯佹牸寮忓寲璐у竵鐨勬柟寮忔湁寰堝绉嶏紝姣斿杩欎簺涓ょ鏂瑰紡銆傜涓€涓柟娉昪onstformatMoney=(money)=>{returnmoney.replace(newRegExp(`(?!^)(?=(\\d{3})+${money.includes('.')?'\\.':'$'})`,'g'),',')}formatMoney('123456789')//'123,456,789'formatMoney('123456789.123')//'123,456,789.123'formatMoney('123')//'123'姝e垯琛ㄨ揪寮忕殑绗簩绉嶆柟寮忚鎴戜滑寰堝ご鐤硷紝涓嶆槸鍚楋紵鎵€浠ユ垜浠渶瑕佹壘鍒颁竴绉嶆洿绠€鍗曠殑鏂规硶鏉ユ牸寮忓寲璐у竵銆俢onstformatMoney=(money)=>{returnmoney.toLocaleString()}formatMoney(123456789)//'123,456,789'formatMoney(123456789.123)//'123,456,789.123'formatMoney(123)//'123'鎴戝お鍠滄杩欑鏂瑰紡浜嗭紝瀹规槗鏄庣櫧銆?/p>