当前位置: 首页 > 科技观察

这些JavaScript函数让你的工作变得更加SoEasy!

时间:2023-03-20 15:05:17 科技观察

本文已获得原作者YoussefZidan授权翻译。randomNumber()获取指定区间内的随机数。***生成最小值和最大值之间的随机整数。*@param{number}minMinnumber*@param{number}maxMaxNumber*/exportconstrandomNumber=(min=0,max=1000)=>Math.ceil(min+Math.random()*(max-min));//Exampleconsole.log(randomNumber());//97capitalize()将字符串首字母大写。/***CapitalizeStrings.*@param{string}sStringthatwillbeCapitalized*/exportconstcapitalize=(s)=>{if(typeofs!=="string")return"";返回.charAt(0).toUpperCase()+s。slice(1);}//Exampleconsole.log(capitalize("cat"));//Cattruncate();这对于长字符串很有用,尤其是在表内。/***截断字符串....*@param{string}要截断的文本字符串*@param{number}截断长度*/exportconsttruncate=(text,num=10)=>{if(text.length>num){return`${text.substring(0,num-3)}...`}returntext;}//Exampleconsole.log(truncate("thisissomelongstringtobetruncated"));//thisis...toTop();滚动到底部,可以通过behavior属性指定滚动速度状态。/***Scrolltotop*/exportconsttoTop=()=>{window.scroll({top:0,left:0,behavior:"smooth"});};softDeepClone()这个方法经常用到,因为有了它,我们可以深度克隆嵌套的数组或对象。但是,此函数不适用于newDate()、NaN、undefined、function、Number、Infinity等数据类型。如果想深度克隆以上数据类型,可以使用lodash中的cloneDeep()函数。/***Deepcloninginputs*@param{any}inputInput*/exportconstsoftDeepClone=(input)=>JSON.parse(JSON.stringify(input));appendURLParams()&getURLParams()方法快速添加和获取查询字符串,我通常使用它们将分页元数据存储到url。/***Appenquerystringandreturnthevalueinaquerystringformat.*@param{string}key*@param{string}value*/exportconstappendURLParams=(key,value)=>{constsearchParams=newURLSearchParams(window.location.search).set(key,value);returnsearchParams.toString();};//exampleconsole.log(appendURLParams("name","youssef"))//name=youssef/***GetparamnamefromURL.*@param{string}name*/exportconstgetURLParams=(name)=>newURLSearchParams(window.location.search).get(name);//Exampleconsole.log(getURLParams(id))//5getInnerHTML()每当服务器返回一串HTML元素时,我都会使用它。/***获取HTML字符串的内部Text*@param{string}strAstringofHTML*/exportconstgetInnerHTML=(str)=>str.replace(/(<([^>]+)>)/gi,"");scrollToHide()向上滚动以显示HTML元素,向下滚动以隐藏它们。/***向下滚动时隐藏HTML元素。*@param{string}元素id*@param{string}distanceinpxex:"100px"*/exportconstscrollToHide=(id,distance)=>{letprevScrollpos=window.pageYOffset;window.onscroll=()=>{constcurrentScrollPos=window。pageYOffset;if(prevScrollpos>currentScrollPos){document.getElementById(id).style.transform=`translateY(${distance})`;}else{document.getElementById(id).style.transform=`translateY(-${distance})`;}prevScrollpos=currentScrollPos;};};humanFileSize()以字节为单位输入文件,返回我们日常熟悉的单位。/***ConvertingBytestoReadableHumanFileSizes.*@param{number}bytesBytesinNumber*/exportconsthumanFileSize=(bytes)=>{letBYTES=bytes;constthresh=1024;if(Math.abs(BYTES)=thresh&&u{consttimes=[];//timearrayconstx=minutesInterval;//minutesintervallettt=startTime;//starttimeconstap=["AM","PM"];//AM-PM//looptoincrementthetimeandpushresultsinarrayfor(leti=0;tt<24*60;i+=1){consthh=Math.floor(tt/60);//gettinghoursofdayin0-24formatconstmm=tt%60;//gettingminuteofthehour0-55formattimes[i]=`${`${hh===12?12:hh%12}`.slice(-2)}:${`0${mm}`.slice(-2)}${ap[Math.floor(hh/12)]}`;//推数据入数组[00:00-12:00AM/PMformat]tt+=x;}returntimes;};//Exampleconsole.log(getTimes());/*["1:00AM","1:15AM","1:30AM","1:45AM","2:00AM","2:15AM","2:30AM",//....]*/setLocalItem()&getLocalItem()让LocalStorage有一个过期时间。/***CachingvalueswithexpirydatetotheLocalHost.*@param{string}keyLocalStorageKey*@param{any}valueLocalStorageValue*@param{number}ttlTimetolive(ExpiryDateinMS)*/exportconstsetLocalItem=(key,value,ttl=duration.month)=>{constnow=newDate();//`item`是一个包含原始值的对象//以及它应该过期的时间constitem={value,expiry:now.getTime()+ttl,};localStorage.setItem(key,JSON.stringify(item));};/***GettingvalueswithexpirydatefromLocalHostthatstoredwith`setLocalItem`.*@param{string}keyLocalStorageKey*/exportconstgetLocalItem=(key)=>{constitemStr=localStorage.getItem(key);//如果item不存在,returnnullif(!itemStr){returnnull;}constitem=JSON.parse(itemStr);constnow=newDate();//比较项目的过期时间和当前时间if(now.getTime()>item.expiry){//如果项目过期,从存储中删除项目//并返回nulllocalStorage.removeItem(key);returnnull;}returnitem.value;};formatNumber()/***Formatnumberswithseparators.*@param{number}num*/exportconstformatNumber=(num)=>num.toLocaleString();//Exampleconsole.log(formatNumber(78899985));//78,899,985我们还可以添加其他选项来获取其他数字格式,如货币、距离,权重等-US",{style:"currency",currency:"USD"});console.log(toUSDCurrency(78899985));//$78,899,985.00console.log(toEGPCurrency(78899985));//????????????????.?.toFormData()每当我需要向服务器发送文件时,我都会使用这个函数。/***ConvertObjectstoFormDataFormat.*@param{object}obj*/exportconsttoFormData=(obj)=>{constformBody=newFormData();Object.keys(obj).forEach((key)=>{formBody.append(key,obj[key])})returnformBody;}getScreenWidth()获取表示屏幕宽度的字符串。/***Detectscreenwidthhandreturnsstringrepresentingthewidthofthescreen.*/exportconstgetScreenWidth=()=>{constscreenWidth=window.screen.width;if(screenWidth<=425)return"mobile";if(screenWidth<=768)return"tablet";if(screenWidth<=1024)return"laptopSm";if(screenWidth<=1440)return"laptopLg";if(screenWidth<=2560)return"HD";returnsscreenWidth;};检查数组中的每个元素是否存在于另一个数组中间。exportconstcontainsAll=(baseArr,arr)=>{letall=false;for(leti=0;i