常用的前端JavaScript方法封裝

1棵红、輸入一個值,返回其數(shù)據(jù)類型**

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

2、數(shù)組去重

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;}

//去除連續(xù)的字符串

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堰乔、深拷貝 淺拷貝

//深克隆(深克隆不考慮函數(shù))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])=='[object Object]'){// 對象result[prop]={};}else{// 數(shù)組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)=='[object Array]'){// 數(shù)組result=[]}else{// 對象result={};}for(varpropintarget){if(target.hasOwnProperty(prop)){result[prop]=deepClone(target[prop])}}returnresult;}// 無法復制函數(shù)varo1=jsON.parse(jsON.stringify(obj1));

5脐恩、reverse底層原理和擴展

// 改變原數(shù)組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、找出字符串中第一次只出現(xiàn)一次的字母

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個兄弟節(jié)點

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}}}

瀏覽器操作

(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)滾動到指定元素區(qū)域

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()}}

15、獲得視口的尺寸

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}}}}

16贴谎、獲取任一元素的任意屬性

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

17汞扎、綁定事件的兼容代碼

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;}}

18、解綁事件

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;}}

19擅这、取消冒泡的兼容代碼

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

20澈魄、檢驗字符串是否是回文

functionisPalina(str){if(Object.prototype.toString.call(str)!=='[object String]'){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;}

23痹扇、運動函數(shù)'

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)}

24铛漓、彈性運動

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);}

25、封裝自己的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)}}

26鲫构、封裝自己的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;}

27浓恶、數(shù)組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;}

28、數(shù)組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;}

29结笨、數(shù)組reduce方法

Array.prototype.myReduce=function(func,initialValue){varlen=this.length,nextValue,i;if(!initialValue){// 沒有傳第二個參數(shù)nextValue=this[0];i=1;}else{// 傳了第二個參數(shù)nextValue=initialValue;i=0;}for(;i<len;i++){nextValue=func(nextValue,this[i],i,this);}returnnextValue;}

30包晰、獲取url中的參數(shù)

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參數(shù)

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

31、數(shù)組排序

// 快排 [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;}

32炕吸、遍歷Dom樹

// 給定頁面上的DOM元素,將訪問元素本身及其所有后代(不僅僅是它的直接子元素)// 對于每個訪問的元素伐憾,函數(shù)講元素傳遞給提供的回調(diào)函數(shù)functiontraverse(element,callback){callback(element);varlist=element.children;for(vari=0;i<list.length;i++){traverse(list[i],callback);}}

33、原生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);}}

34算途、異步加載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);}

35塞耕、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;}}

36、實現(xiàn)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;}

37嘴瓤、實現(xiàn)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;}

38、實現(xiàn)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;}

39莉钙、防抖

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

40廓脆、節(jié)流

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

41、requestAnimFrame兼容性方法

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

42磁玉、cancelAnimFrame兼容性方法

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

43停忿、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);}

44、獲取url上的參數(shù)

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]||'';}}

45蚊伞、格式化時間

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]});}

46席赂、驗證郵箱的正則表達式

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

47、函數(shù)柯里化

//是把接受多個參數(shù)的函數(shù)變換成接受一個單一參數(shù)(最初函數(shù)的第一個參數(shù))的函數(shù)时迫,并且返回接受余下的參數(shù)且返回結(jié)果的新函數(shù)的技術

functioncurryIt(fn){varlength=fn.length,args=[];varresult=function(arg){args.push(arg);length--;if(length<=0){returnfn.apply(this,args);}else{returnresult;}}returnresult;}

48颅停、大數(shù)相加

functionsumBigNumber(a,b){varres='',//結(jié)果temp=0;//按位加的結(jié)果及進位a=a.split('');b=b.split('');while(a.length||b.length||temp){//~~按位非 1.類型轉(zhuǎn)換,轉(zhuǎn)換成數(shù)字 2.~~undefined==0 temp+=~~a.pop()+~~b.pop();res=(temp%10)+res;temp=temp>9;}returnres.replace(/^0+/,'');}

49掠拳、單例模式

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

50癞揉、設備判斷:android、ios溺欧、web

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

判斷是否為微信

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

52.是否為PC端

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

53.判斷圖片加載完成

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()}}}}

54.音頻加載完成操作

constloadAudio=function(src,callback){// 音頻加載varaudio=newAudio(src)audio.onloadedmetadata=callback? audio.src=src}

55,圖片地址轉(zhuǎn)base64

constgetBase64=function(img){//傳入圖片路徑喊熟,返回base64,使用getBase64(url).then(function(base64){},function(err){}); letgetBase64Image=function(img,width,height){//width姐刁、height調(diào)用時傳入具體像素值芥牌,控制大小,不傳則默認圖像大小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();}}

56.H5軟鍵盤縮回、彈起回調(diào)

consth5Resize=function(downCb,upCb){//當軟件鍵盤彈起會改變當前 window.innerHeight聂使,監(jiān)聽這個值變化 [downCb 當軟鍵盤彈起后壁拉,縮回的回調(diào),upCb 當軟鍵盤彈起的回調(diào)]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();}});}

計算2個日期之間相差多少天

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

生成隨機十六進制顏色

//可以使用 Math.random 和 padEnd 屬性生成隨機的十六進制顏色谬俄。constrandomHex=()=>`#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,"0")}`;console.log(randomHex());// Result: #92b008

手機號中間四位變成*

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

數(shù)字轉(zhuǎn)化為大寫金額

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(/^整$/,'零元整');};

數(shù)字轉(zhuǎn)化為中文數(shù)字

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)};

操作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()}`};

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市扇商,隨后出現(xiàn)的幾起案子凤瘦,更是在濱河造成了極大的恐慌,老刑警劉巖案铺,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蔬芥,死亡現(xiàn)場離奇詭異,居然都是意外死亡控汉,警方通過查閱死者的電腦和手機笔诵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來姑子,“玉大人乎婿,你說我怎么就攤上這事〗钟樱” “怎么了谢翎?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長沐旨。 經(jīng)常有香客問我森逮,道長,這世上最難降的妖魔是什么磁携? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任褒侧,我火速辦了婚禮,結(jié)果婚禮上谊迄,老公的妹妹穿的比我還像新娘闷供。我一直安慰自己,他們只是感情好统诺,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布歪脏。 她就那樣靜靜地躺著,像睡著了一般篙议。 火紅的嫁衣襯著肌膚如雪唾糯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天鬼贱,我揣著相機與錄音移怯,去河邊找鬼。 笑死这难,一個胖子當著我的面吹牛舟误,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播姻乓,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嵌溢,長吁一口氣:“原來是場噩夢啊……” “哼眯牧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起赖草,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤学少,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后秧骑,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體版确,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年乎折,在試婚紗的時候發(fā)現(xiàn)自己被綠了绒疗。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡骂澄,死狀恐怖吓蘑,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情坟冲,我是刑警寧澤磨镶,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站健提,受9級特大地震影響棋嘲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜矩桂,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望痪伦。 院中可真熱鬧侄榴,春花似錦、人聲如沸网沾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽辉哥。三九已至桦山,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間醋旦,已是汗流浹背恒水。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留饲齐,地道東北人钉凌。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像捂人,于是被迫代替她去往敵國和親御雕。 傳聞我的和親對象是個殘疾皇子矢沿,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容