常用的前端JavaScript方法封装

制作网站的时候经常会涉及一些JS方法,这边文章分享一些常用的前端JavaScript方法封装,希望对大家有用。 1、输入一个值,返回其数据类型** functiontype(par…

制作网站的时候经常会涉及一些JS方法,这边文章分享一些常用的前端JavaScript方法封装,希望对大家有用。

1、输入一个值,返回其数据类型**

functiontype(para){returnObject.prototype.toString.call(para)}

2、数组去重

functionunique1(arr){return[…newSet(arr)]}functionunique2(arr){varobj={};returnarr.filter(ele=>{if(!obj[ele]){obj[ele]=true;returntrue;}})}functionunique3(arr){varresult=[];arr.forEach(ele=>{if(result.indexOf(ele)==-1){result.push(ele)}})returnresult;}

3、字符串去重

String.prototype.unique=function(){varobj={},str='',len=this.length;for(vari=0;i<len;i++){if(!obj[this[i]]){str+=this[i];obj[this[i]]=true;}}returnstr;}

去除连续的字符串

functionuniq(str){returnstr.replace(/(\\w)\\1+/g,'$1')}

去除字符串空格

consttrim=function(str,type){//去除空格,type:1-所有空格2-前后空格3-前空格4-后空格type=type||1switch(type){case1:returnstr.replace(/\\s+/g,'')case2:returnstr.replace(/(^\\s*)|(\\s*$)/g,'')case3:returnstr.replace(/(^\\s*)/g,'')case4:returnstr.replace(/(\\s*$)/g,'')default:returnstr}}

4、深拷贝 浅拷贝

//深克隆(深克隆不考虑函数)functiondeepClone(obj,result){varresult=result||{};for(varpropinobj){if(obj.hasOwnProperty(prop)){if(typeofobj[prop]=='object'&&obj[prop]!==null){//引用值(obj/array)且不为nullif(Object.prototype.toString.call(obj[prop])=='[objectObject]'){//对象result[prop]={};}else{//数组result[prop]=[];}deepClone(obj[prop],result[prop])}else{//原始值或funcresult[prop]=obj[prop]}}}returnresult;}//深浅克隆是针对引用值functiondeepClone(target){if(typeof(target)!=='object'){returntarget;}varresult;if(Object.prototype.toString.call(target)=='[objectArray]'){//数组result=[]}else{//对象result={};}for(varpropintarget){if(target.hasOwnProperty(prop)){result[prop]=deepClone(target[prop])}}returnresult;}//无法复制函数varo1=jsON.parse(jsON.stringify(obj1));

5、reverse底层原理和扩展

//改变原数组Array.prototype.myReverse=function(){varlen=this.length;for(vari=0;i<len;i++){vartemp=this[i];this[i]=this[len-1-i];this[len-1-i]=temp;}returnthis;}

6、圣杯模式的继承

functioninherit(Target,Origin){functionF(){};F.prototype=Origin.prototype;Target.prototype=newF();Target.prototype.constructor=Target;//最终的原型指向Target.prop.uber=Origin.prototype;}

7、找出字符串中第一次只出现一次的字母

String.prototype.firstAppear=function(){varobj={},len=this.length;for(vari=0;i<len;i++){if(obj[this[i]]){obj[this[i]]++;}else{obj[this[i]]=1;}}for(varpropinobj){if(obj[prop]==1){returnprop;}}}

8、找元素的第n级父元素

functionparents(ele,n){while(ele&&n){ele=ele.parentElement?ele.parentElement:ele.parentNode;n–;}returnele;}

9、 返回元素的第n个兄弟节点

functionretSibling(e,n){while(e&&n){if(n>0){if(e.nextElementSibling){e=e.nextElementSibling;}else{for(e=e.nextSibling;e&&e.nodeType!==1;e=e.nextSibling);}n–;}else{if(e.previousElementSibling){e=e.previousElementSibling;}else{for(e=e.previousElementSibling;e&&e.nodeType!==1;e=e.previousElementSibling);}n++;}}returne;}

10、封装mychildren,解决浏览器的兼容问题

functionmyChildren(e){varchildren=e.childNodes,arr=[],len=children.length;for(vari=0;i<len;i++){if(children[i].nodeType===1){arr.push(children[i])}}returnarr;}

11、判断元素有没有子元素

functionhasChildren(e){varchildren=e.childNodes,len=children.length;for(vari=0;i<len;i++){if(children[i].nodeType===1){returntrue;}}returnfalse;}

12、我一个元素插入到另一个元素的后面

Element.prototype.insertAfter=function(target,elen){varnextElen=elen.nextElenmentSibling;if(nextElen==null){this.appendChild(target);}else{this.insertBefore(target,nextElen);}}

13、返回当前的时间(年月日时分秒)

functiongetDateTime(){vardate=newDate(),year=date.getFullYear(),month=date.getMonth()+1,day=date.getDate(),hour=date.getHours()+1,minute=date.getMinutes(),second=date.getSeconds();month=checkTime(month);day=checkTime(day);hour=checkTime(hour);minute=checkTime(minute);second=checkTime(second);functioncheckTime(i){if(i<10){i="0"+i;}returni;}return""+year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒"}

14、获得滚动条的滚动距离

functiongetScrollOffset(){if(window.pageXOffset){return{x:window.pageXOffset,y:window.pageYOffset}}else{return{x:document.body.scrollLeft+document.documentElement.scrollLeft,y:document.body.scrollTop+document.documentElement.scrollTop}}}

15、浏览器操作

(1)滚动到页面顶部

exportconstscrollToTop=()=>{constheight=document.documentElement.scrollTop||document.body.scrollTop;if(height>0){window.requestAnimationFrame(scrollToTop);window.scrollTo(0,height-height/8);}}

(2)滚动到页面底部

exportconstscrollToBottom=()=>{window.scrollTo(0,document.documentElement.clientHeight);}

(3)滚动到指定元素区域

exportconstsmoothScroll=(element)=>{document.querySelector(element).scrollIntoView({behavior:'smooth'});};

(4)获取可视窗口高度

exportconstgetClientHeight=()=>{letclientHeight=0;if(document.body.clientHeight&&document.documentElement.clientHeight){clientHeight=(document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;}else{clientHeight=(document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;}returnclientHeight;}

(5)获取可视窗口宽度

exportconstgetPageViewWidth=()=>{return(document.compatMode=="BackCompat"?document.body:document.documentElement).clientWidth;}

(6)打开浏览器全屏

exportconsttoFullScreen=()=>{letelement=document.body;if(element.requestFullscreen){element.requestFullscreen()}elseif(element.mozRequestFullScreen){element.mozRequestFullScreen()}elseif(element.msRequestFullscreen){element.msRequestFullscreen()}elseif(element.webkitRequestFullscreen){element.webkitRequestFullScreen()}}

(7)退出浏览器全屏

exportconstexitFullscreen=()=>{if(document.exitFullscreen){document.exitFullscreen()}elseif(document.msExitFullscreen){document.msExitFullscreen()}elseif(document.mozCancelFullScreen){document.mozCancelFullScreen()}elseif(document.webkitExitFullscreen){document.webkitExitFullscreen()}}

16、获得视口的尺寸

functiongetViewportOffset(){if(window.innerWidth){return{w:window.innerWidth,h:window.innerHeight}}else{//ie8及其以下if(document.compatMode==="BackCompat"){//怪异模式return{w:document.body.clientWidth,h:document.body.clientHeight}}else{//标准模式return{w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}}}}

17、获取任一元素的任意属性

functiongetStyle(elem,prop){returnwindow.getComputedStyle?window.getComputedStyle(elem,null)[prop]:elem.currentStyle[prop]}

18、绑定事件的兼容代码

functionaddEvent(elem,type,handle){if(elem.addEventListener){//非ie和非ie9elem.addEventListener(type,handle,false);}elseif(elem.attachEvent){//ie6到ie8elem.attachEvent('on'+type,function(){handle.call(elem);})}else{elem['on'+type]=handle;}}

19、解绑事件

functionremoveEvent(elem,type,handle){if(elem.removeEventListener){//非ie和非ie9elem.removeEventListener(type,handle,false);}elseif(elem.detachEvent){//ie6到ie8elem.detachEvent('on'+type,handle);}else{elem['on'+type]=null;}}

20、取消冒泡的兼容代码

functionstopBubble(e){if(e&&e.stopPropagation){e.stopPropagation();}else{window.event.cancelBubble=true;}}

20、检验字符串是否是回文

functionisPalina(str){if(Object.prototype.toString.call(str)!=='[objectString]'){returnfalse;}varlen=str.length;for(vari=0;i<len/2;i++){if(str[i]!=str[len-1-i]){returnfalse;}}returntrue;}

21、检验字符串是否是回文

functionisPalindrome(str){str=str.replace(/\\W/g,'').toLowerCase();console.log(str)return(str==str.split('').reverse().join(''))}

22、兼容getElementsByClassName方法

Element.prototype.getElementsByClassName=Document.prototype.getElementsByClassName=function(_className){varallDomArray=document.getElementsByTagName('*');varlastDomArray=[];functiontrimSpace(strClass){varreg=/\\s+/g;returnstrClass.replace(reg,'').trim()}for(vari=0;i<allDomArray.length;i++){varclassArray=trimSpace(allDomArray[i].className).split('');for(varj=0;j<classArray.length;j++){if(classArray[j]==_className){lastDomArray.push(allDomArray[i]);break;}}}returnlastDomArray;}

24、运动函数

functionanimate(obj,json,callback){clearInterval(obj.timer);varspeed,current;obj.timer=setInterval(function(){varlock=true;for(varpropinjson){if(prop=='opacity'){current=parseFloat(window.getComputedStyle(obj,null)[prop])*100;}else{current=parseInt(window.getComputedStyle(obj,null)[prop]);}speed=(json[prop]-current)/7;speed=speed>0?Math.ceil(speed):Math.floor(speed);if(prop=='opacity'){obj.style[prop]=(current+speed)/100;}else{obj.style[prop]=current+speed+'px';}if(current!=json[prop]){lock=false;}}if(lock){clearInterval(obj.timer);typeofcallback=='function'?callback():'';}},30)}

25、弹性运动

functionElasticMovement(obj,target){clearInterval(obj.timer);variSpeed=40,a,u=0.8;obj.timer=setInterval(function(){a=(target-obj.offsetLeft)/8;iSpeed=iSpeed+a;iSpeed=iSpeed*u;if(Math.abs(iSpeed)<=1&&Math.abs(a)<=1){console.log('over')clearInterval(obj.timer);obj.style.left=target+'px';}else{obj.style.left=obj.offsetLeft+iSpeed+'px';}},30);}

26、封装自己的forEach方法

Array.prototype.myForEach=function(func,obj){varlen=this.length;var_this=arguments[1]?arguments[1]:window;//var_this=arguments[1]||window;for(vari=0;i<len;i++){func.call(_this,this[i],i,this)}}

27、封装自己的filter方法

Array.prototype.myFilter=function(func,obj){varlen=this.length;vararr=[];var_this=arguments[1]||window;for(vari=0;i<len;i++){func.call(_this,this[i],i,this)&&arr.push(this[i]);}returnarr;}

28、数组map方法

Array.prototype.myMap=function(func){vararr=[];varlen=this.length;var_this=arguments[1]||window;for(vari=0;i<len;i++){arr.push(func.call(_this,this[i],i,this));}returnarr;}

29、数组every方法

Array.prototype.myEvery=function(func){varflag=true;varlen=this.length;var_this=arguments[1]||window;for(vari=0;i<len;i++){if(func.apply(_this,[this[i],i,this])==false){flag=false;break;}}returnflag;}

30、数组reduce方法

Array.prototype.myReduce=function(func,initialValue){varlen=this.length,nextValue,i;if(!initialValue){//没有传第二个参数nextValue=this[0];i=1;}else{//传了第二个参数nextValue=initialValue;i=0;}for(;i<len;i++){nextValue=func(nextValue,this[i],i,this);}returnnextValue;}

31、获取url中的参数

functiongetWindonHref(){varsHref=window.location.href;varargs=sHref.split('?');if(args[0]===sHref){return'';}varhrefarr=args[1].split('#')[0].split('&');varobj={};for(vari=0;i<hrefarr.length;i++){hrefarr[i]=hrefarr[i].split('=');obj[hrefarr[i][0]]=hrefarr[i][1];}returnobj;}constgetParameters=(URL)=>{URL=JSON.parse('{"'+decodeURI(URL.split("?")[1]).replace(/"/g,'\\\\"').replace(/&/g,'","').replace(/=/g,'":"')+'"}');returnJSON.stringify(URL);};getParameters(window.location);//Result:{search:"easy",page:3}

或者更为简单的:

Object.fromEntries(newURLSearchParams(window.location.search))//Result:{search:"easy",page:3}

键值对拼接成URL参数

exportconstparams2Url=(obj)=>{letparams=[]for(letkeyinobj){params.push(`${key}=${obj[key]}`);}returnencodeURIComponent(params.join('&'))}

32、数组排序

//快排[left]+min+[right]functionquickArr(arr){if(arr.length<=1){returnarr;}varleft=[],right=[];varpIndex=Math.floor(arr.length/2);varp=arr.splice(pIndex,1)[0];for(vari=0;i<arr.length;i++){if(arr[i]<=p){left.push(arr[i]);}else{right.push(arr[i]);}}//递归returnquickArr(left).concat([p],quickArr(right));}//冒泡functionbubbleSort(arr){for(vari=0;i<arr.length-1;i++){for(varj=i+1;j<arr.length;j++){if(arr[i]>arr[j]){vartemp=arr[i];arr[i]=arr[j];arr[j]=temp;}}}returnarr;}functionbubbleSort(arr){varlen=arr.length;for(vari=0;i<len-1;i++){for(varj=0;j<len-1-i;j++){if(arr[j]>arr[j+1]){vartemp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}returnarr;}

33、遍历Dom树

//给定页面上的DOM元素,将访问元素本身及其所有后代(不仅仅是它的直接子元素)//对于每个访问的元素,函数讲元素传递给提供的回调函数functiontraverse(element,callback){callback(element);varlist=element.children;for(vari=0;i<list.length;i++){traverse(list[i],callback);}}

34、原生js封装ajax

functionajax(method,url,callback,data,flag){varxhr;flag=flag||true;method=method.toUpperCase();if(window.XMLHttpRequest){xhr=newXMLHttpRequest();}else{xhr=newActiveXObject('Microsoft.XMLHttp');}xhr.onreadystatechange=function(){if(xhr.readyState==4&&xhr.status==200){console.log(2)callback(xhr.responseText);}}if(method=='GET'){vardate=newDate(),timer=date.getTime();xhr.open('GET',url+'?'+data+'&timer'+timer,flag);xhr.send()}elseif(method=='POST'){xhr.open('POST',url,flag);xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xhr.send(data);}}

35、异步加载script

functionloadScript(url,callback){varoscript=document.createElement('script');if(oscript.readyState){//ie8及以下版本oscript.onreadystatechange=function(){if(oscript.readyState==='complete'||oscript.readyState==='loaded'){callback();}}}else{oscript.onload=function(){callback()};}oscript.src=url;document.body.appendChild(oscript);}

36、cookie管理

varcookie={set:function(name,value,time){document.cookie=name+'='+value+';max-age='+time;returnthis;},remove:function(name){returnthis.setCookie(name,'',-1);},get:function(name,callback){varallCookieArr=document.cookie.split(';');for(vari=0;i<allCookieArr.length;i++){varitemCookieArr=allCookieArr[i].split('=');if(itemCookieArr[0]===name){returnitemCookieArr[1]}}returnundefined;}}

37、实现bind()方法

Function.prototype.myBind=function(target){vartarget=target||window;var_args1=[].slice.call(arguments,1);varself=this;vartemp=function(){};varF=function(){var_args2=[].slice.call(arguments,0);varparasArr=_args1.concat(_args2);returnself.apply(thisinstanceoftemp?this:target,parasArr)}temp.prototype=self.prototype;F.prototype=newtemp();returnF;}

38、实现call()方法

Function.prototype.myCall=function(){varctx=arguments[0]||window;ctx.fn=this;varargs=[];for(vari=1;i<arguments.length;i++){args.push(arguments[i])}varresult=ctx.fn(…args);deletectx.fn;returnresult;}

39、实现apply()方法

Function.prototype.myApply=function(){varctx=arguments[0]||window;ctx.fn=this;if(!arguments[1]){varresult=ctx.fn();deletectx.fn;returnresult;}varresult=ctx.fn(…arguments[1]);deletectx.fn;returnresult;}

40、防抖

functiondebounce(handle,delay){vartimer=null;returnfunction(){var_self=this,_args=arguments;clearTimeout(timer);timer=setTimeout(function(){handle.apply(_self,_args)},delay)}}

41、节流

functionthrottle(handler,wait){varlastTime=0;returnfunction(e){varnowTime=newDate().getTime();if(nowTime-lastTime>wait){handler.apply(this,arguments);lastTime=nowTime;}}}

42、requestAnimFrame兼容性方法

window.requestAnimFrame=(function(){returnwindow.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();

43、cancelAnimFrame兼容性方法

window.cancelAnimFrame=(function(){returnwindow.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(id){window.clearTimeout(id);};})();

44、jsonp底层方法

functionjsonp(url,callback){varoscript=document.createElement('script');if(oscript.readyState){//ie8及以下版本oscript.onreadystatechange=function(){if(oscript.readyState==='complete'||oscript.readyState==='loaded'){callback();}}}else{oscript.onload=function(){callback()};}oscript.src=url;document.body.appendChild(oscript);}

45、获取url上的参数

functiongetUrlParam(sUrl,sKey){varresult={};sUrl.replace(/(\\w+)=(\\w+)(?=[&|#])/g,function(ele,key,val){if(!result[key]){result[key]=val;}else{vartemp=result[key];result[key]=[].concat(temp,val);}})if(!sKey){returnresult;}else{returnresult[sKey]||'';}}

46、格式化时间

functionformatDate(t,str){varobj={yyyy:t.getFullYear(),yy:(""+t.getFullYear()).slice(-2),M:t.getMonth()+1,MM:("0"+(t.getMonth()+1)).slice(-2),d:t.getDate(),dd:("0"+t.getDate()).slice(-2),H:t.getHours(),HH:("0"+t.getHours()).slice(-2),h:t.getHours()%12,hh:("0"+t.getHours()%12).slice(-2),m:t.getMinutes(),mm:("0"+t.getMinutes()).slice(-2),s:t.getSeconds(),ss:("0"+t.getSeconds()).slice(-2),w:['日','一','二','三','四','五','六'][t.getDay()]};returnstr.replace(/([a-z]+)/ig,function($1){returnobj[$1]});}

47、验证邮箱的正则表达式

functionisAvailableEmail(sEmail){varreg=/^([\\w+\\.])+@\\w+([.]\\w+)+$/returnreg.test(sEmail)}

48、函数柯里化

//是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术functioncurryIt(fn){varlength=fn.length,args=[];varresult=function(arg){args.push(arg);length–;if(length<=0){returnfn.apply(this,args);}else{returnresult;}}returnresult;}

49、大数相加

functionsumBigNumber(a,b){varres='',//结果temp=0;//按位加的结果及进位a=a.split('');b=b.split('');while(a.length||b.length||temp){//~~按位非1.类型转换,转换成数字2.~~undefined==0temp+=~~a.pop()+~~b.pop();res=(temp%10)+res;temp=temp>9;}returnres.replace(/^0+/,'');}

50、单例模式

functiongetSingle(func){varresult;returnfunction(){if(!result){result=newfunc(arguments);}returnresult;}}

51、设备判断:android、ios、web

constisDevice=function(){//判断是android还是ios还是webvarua=navigator.userAgent.toLowerCase()if(ua.match(/iPhone\\sOS/i)==='iphoneos'||ua.match(/iPad/i)==='ipad'){//iosreturn'iOS'}if(ua.match(/Android/i)==='android'){return'Android'}return'Web'}

52、判断是否为微信

constisWx=function(){//判断是否为微信varua=window.navigator.userAgent.toLowerCase()if(ua.match(/MicroMessenger/i)==='micromessenger'){returntrue}returnfalse}

53、是否为PC端

constisPC=function(){//是否为PC端letuserAgentInfo=navigator.userAgentletAgents=['Android','iPhone','SymbianOS','WindowsPhone','iPad','iPod']letflag=truefor(letv=0;v<Agents.length;v++){if(userAgentInfo.indexOf(Agents[v])>0){flag=falsebreak}}returnflag}

54、判断图片加载完成

constimgLoadAll=function(arr,callback){//图片加载letarrImg=[]for(leti=0;i<arr.length;i++){letimg=newImage()img.src=arr[i]img.onload=function(){arrImg.push(this)if(arrImg.length==arr.length){callback&&callback()}}}}

55、音频加载完成操作

constloadAudio=function(src,callback){//音频加载varaudio=newAudio(src)audio.onloadedmetadata=callbackaudio.src=src}

56、图片地址转base64

constgetBase64=function(img){//传入图片路径,返回base64,使用getBase64(url).then(function(base64){},function(err){});letgetBase64Image=function(img,width,height){//width、height调用时传入具体像素值,控制大小,不传则默认图像大小letcanvas=document.createElement("canvas");canvas.width=width?width:img.width;canvas.height=height?height:img.height;letctx=canvas.getContext("2d");ctx.drawImage(img,0,0,canvas.width,canvas.height);letdataURL=canvas.toDataURL();returndataURL;}letimage=newImage();image.crossOrigin='';image.src=img;letdeferred=$.Deferred();if(img){image.onload=function(){deferred.resolve(getBase64Image(image));}returndeferred.promise();}}

57、H5软键盘缩回、弹起回调

consth5Resize=function(downCb,upCb){//当软件键盘弹起会改变当前window.innerHeight,监听这个值变化[downCb当软键盘弹起后,缩回的回调,upCb当软键盘弹起的回调]varclientHeight=window.innerHeight;downCb=typeofdownCb==='function'?downCb:function(){}upCb=typeofupCb==='function'?upCb:function(){}window.addEventListener('resize',()=>{varheight=window.innerHeight;if(height===clientHeight){downCb();}if(height<clientHeight){upCb();}});}

58、计算2个日期之间相差多少天

constdayDif=(date1,date2)=>Math.ceil(Math.abs(date1.getTime()-date2.getTime())/86400000)dayDif(newDate("2020-10-21"),newDate("2021-10-22"))//Result:366

59、生成随机十六进制颜色

//可以使用Math.random和padEnd属性生成随机的十六进制颜色。constrandomHex=()=>`#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,"0")}`;console.log(randomHex());//Result:#92b008

60、手机号中间四位变成*

exportconsttelFormat=(tel)=>{tel=String(tel);returntel.substr(0,3)+"****"+tel.substr(7);}

61、数字转化为大写金额

exportconstdigitUppercase=(n)=>{constfraction=['角','分'];constdigit=['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];constunit=[['元','万','亿'],['','拾','佰','仟']];n=Math.abs(n);lets='';for(leti=0;i<fraction.length;i++){s+=(digit[Math.floor(n*10*Math.pow(10,i))%10]+fraction[i]).replace(/零./,'');}s=s||'整';n=Math.floor(n);for(leti=0;i<unit[0].length&&n>0;i++){letp='';for(letj=0;j<unit[1].length&&n>0;j++){p=digit[n%10]+unit[1][j]+p;n=Math.floor(n/10);}s=p.replace(/(零.)*零$/,'').replace(/^$/,'零')+unit[0][i]+s;}returns.replace(/(零.)*零元/,'元').replace(/(零.)+/g,'零').replace(/^整$/,'零元整');};

62、数字转化为中文数字

exportconstintToChinese=(value)=>{conststr=String(value);constlen=str.length-1;constidxs=['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿'];constnum=['零','一','二','三','四','五','六','七','八','九'];returnstr.replace(/([1-9]|0+)/g,($,$1,idx,full)=>{letpos=0;if($1[0]!=='0'){pos=len-idx;if(idx==0&&$1[0]==1&&idxs[len-idx]=='十'){returnidxs[len-idx];}returnnum[$1[0]]+idxs[len-idx];}else{letleft=len-idx;letright=len-idx+$1.length;if(Math.floor(right/4)-Math.floor(left/4)>0){pos=left-left%4;}if(pos){returnidxs[pos]+num[$1[0]];}elseif(idx+$1.length>=len){return'';}else{returnnum[$1[0]]}}});}

(1)存储loalStorage

exportconstloalStorageSet=(key,value)=>{if(!key)return;if(typeofvalue!=='string'){value=JSON.stringify(value);}window.localStorage.setItem(key,value);};

(2)获取localStorage

exportconstloalStorageGet=(key)=>{if(!key)return;returnwindow.localStorage.getItem(key);};

(3)删除localStorage

exportconstloalStorageRemove=(key)=>{if(!key)return;window.localStorage.removeItem(key);};

(4)存储sessionStorage

exportconstsessionStorageSet=(key,value)=>{if(!key)return;if(typeofvalue!=='string'){value=JSON.stringify(value);}window.sessionStorage.setItem(key,value)};

(5)获取sessionStorage

exportconstsessionStorageGet=(key)=>{if(!key)return;returnwindow.sessionStorage.getItem(key)};

(6)删除sessionStorage

exportconstsessionStorageRemove=(key)=>{if(!key)return;window.sessionStorage.removeItem(key)};

63、操作cookie

(1)设置cookie

exportconstsetCookie=(key,value,expire)=>{constd=newDate();d.setDate(d.getDate()+expire);document.cookie=`${key}=${value};expires=${d.toUTCString()}`};

(2)读取cookie

exportconstgetCookie=(key)=>{constcookieStr=unescape(document.cookie);constarr=cookieStr.split(';');letcookieValue='';for(leti=0;i<arr.length;i++){consttemp=arr[i].split('=');if(temp[0]===key){cookieValue=temp[1];break}}returncookieValue};

(3)删除cookie

exportconstdelCookie=(key)=>{document.cookie=`${encodeURIComponent(key)}=;expires=${newDate()}`};

产品猿社区致力收录更多优质的商业产品,给服务商以及软件采购客户提供更多优质的软件产品,帮助开发者变现来实现多方共赢;

日常运营的过程中我们难免会遇到各种版权纠纷等问题,如果您在社区内发现有您的产品未经您授权而被用户提供下载或使用,您可按照我们投诉流程处理,点我投诉

本文来自用户发布投稿,不代表产品猿立场 ;若对此文有疑问或内容有严重错误,可联系平台客服反馈;

部分产品是用户投稿,可能本文没有提供官方下下载地址或教程,若您看到的内容没有下载入口,您可以在我们产品园商城搜索看开发者是否有发布商品;若您是开发者,也诚邀您入驻商城平台发布的产品,地址:点我进入

如若转载,请注明出处:https://www.chanpinyuan.cn/42029.html;
(0)
上一篇 2023年4月25日 下午4:17
下一篇 2023年4月25日 下午4:17

相关推荐

发表回复

登录后才能评论
分享本页
返回顶部