20个JS工具函数助力高效开发
1、校验数据类型exportconsttypeOffunction(obj){returnObject。prototype。toString。call(obj)。slice(8,1)。toLowerCase()}
示例:typeOf(树哥)stringtypeOf(〔〕)arraytypeOf(newDate())datetypeOf(null)nulltypeOf(true)booleantypeOf((){})function2、防抖exportconstdebounce((){lettimernullreturn(callback,wait800){timerclearTimeout(timer)timersetTimeout(callback,wait)}})()
示例:
如vue中使用methods:{loadList(){debounce((){console。log(加载数据)},500)}}3、节流exportconstthrottle((){letlast0return(callback,wait800){letnownewDate()if(nowlastwait){callback()lastnow}}})()4、手机号脱敏exportconsthideMobile(mobile){returnmobile。replace((d{3})d{4}(d{4}),12)}5、开启全屏exportconstlaunchFullscreen(element){if(element。requestFullscreen){element。requestFullscreen()}elseif(element。mozRequestFullScreen){element。mozRequestFullScreen()}elseif(element。msRequestFullscreen){element。msRequestFullscreen()}elseif(element。webkitRequestFullscreen){element。webkitRequestFullScreen()}}6、关闭全屏exportconstexitFullscreen(){if(document。exitFullscreen){document。exitFullscreen()}elseif(document。msExitFullscreen){document。msExitFullscreen()}elseif(document。mozCancelFullScreen){document。mozCancelFullScreen()}elseif(document。webkitExitFullscreen){document。webkitExitFullscreen()}}7、大小写转换
参数:str待转换的字符串type1全大写2全小写3首字母大写exportconstturnCase(str,type){switch(type){case1:returnstr。toUpperCase()case2:returnstr。toLowerCase()case3:returnstr〔0〕。toUpperCase()str。substr(1)。toLowerCase()substr已不推荐使用returnstr〔0〕。toUpperCase()str。substring(1)。toLowerCase()default:returnstr}}
示例:turnCase(vue,1)VUEturnCase(REACT,2)reactturnCase(vue,3)Vue8、解析URL参数exportconstgetSearchParams(){constsearchParnewURLSearchParams(window。location。search)constparamsObj{}for(const〔key,value〕ofsearchPar。entries()){paramsObj〔key〕value}returnparamsObj}
示例:假设目前位于https:comindex?id154513age18;getSearchParams();{id:154513,age:18}9、判断手机是Andoird还是IOS1:ios2:android3:其它exportconstgetOSType(){letunavigator。userAgent,appnavigator。appVersion;letisAndroidu。indexOf(Android)1u。indexOf(Linux)1;letisIOS!!u。match((i〔;〕;(U;)?CPU。MacOSX);if(isIOS){return1;}if(isAndroid){return2;}return3;}10、数组对象根据字段去重
参数:arr要去重的数组key根据去重的字段名exportconstuniqueArrayObject(arr〔〕,keyid){if(arr。length0)returnletlist〔〕constmap{}arr。forEach((item){if(!map〔item〔key〕〕){map〔item〔key〕〕item}})listObject。values(map)returnlist}
示例:constresponseList〔{id:1,name:树哥},{id:2,name:黄老爷},{id:3,name:张麻子},{id:1,name:黄老爷},{id:2,name:张麻子},{id:3,name:树哥},{id:1,name:树哥},{id:2,name:黄老爷},{id:3,name:张麻子},〕uniqueArrayObject(responseList,id)〔{id:1,name:树哥},{id:2,name:黄老爷},{id:3,name:张麻子}〕11、滚动到页面顶部exportconstscrollToTop(){constheightdocument。documentElement。scrollTopdocument。body。scrollTop;if(height0){window。requestAnimationFrame(scrollToTop);window。scrollTo(0,heightheight8);}}12、滚动到元素位置exportconstsmoothScrollelement{document。querySelector(element)。scrollIntoView({behavior:smooth});};
示例:smoothScroll(target);平滑滚动到ID为target的元素13、uuidexportconstuuid(){consttempurlURL。createObjectURL(newBlob())constuuidtempurl。toString()URL。revokeObjectURL(tempurl)释放这个urlreturnuuid。substring(uuid。lastIndexOf()1)}
示例:uuid()a640be34689f4b98be77e3972f9bffdd
不过要吐槽一句的是,uuid一般应由后端来进行生成14、金额格式化
参数:{number}number:要格式化的数字{number}decimals:保留几位小数{string}decpoint:小数点符号{string}thousandssep:千分位符号exportconstmoneyFormat(number,decimals,decpoint,thousandssep){number(number)。replace(〔09Ee。〕g,)constn!isFinite(number)?0:numberconstprec!isFinite(decimals)?2:Math。abs(decimals)constseptypeofthousandssepundefined?,:thousandssepconstdectypeofdecpointundefined?。:decpointletsconsttoFixedFixfunction(n,prec){constkMath。pow(10,prec)returnMath。ceil(nk)k}s(prec?toFixedFix(n,prec):Math。round(n))。split(。)constre(?d)(d{3})while(re。test(s〔0〕)){s〔0〕s〔0〕。replace(re,1sep2)}if((s〔1〕)。lengthprec){s〔1〕s〔1〕s〔1〕newArray(precs〔1〕。length1)。join(0)}returns。join(dec)}
示例:moneyFormat(10000000)10,000,000。00moneyFormat(10000000,3,。,)10000000。00015、存储操作classMyCache{constructor(isLocaltrue){this。storageisLocal?localStorage:sessionStorage}setItem(key,value){if(typeof(value)object)valueJSON。stringify(value)this。storage。setItem(key,value)}getItem(key){try{returnJSON。parse(this。storage。getItem(key))}catch(err){returnthis。storage。getItem(key)}}removeItem(key){this。storage。removeItem(key)}clear(){this。storage。clear()}key(index){returnthis。storage。key(index)}length(){returnthis。storage。length}}constlocalCachenewMyCache()constsessionCachenewMyCache(false)export{localCache,sessionCache}
示例:localCache。getItem(user)sessionCache。setItem(name,树哥)sessionCache。getItem(token)localCache。clear()16、下载文件
参数:api接口params请求参数fileName文件名constdownloadFile(api,params,fileName,typeget){axios({method:type,url:api,responseType:blob,params:params})。then((res){letstrres。headers〔contentdisposition〕if(!res!str){return}letsuffix截取文件名和文件类型if(str。lastIndexOf(。)){fileName?:fileNamedecodeURI(str。substring(str。indexOf()1,str。lastIndexOf(。)))suffixstr。substring(str。lastIndexOf(。),str。length)}如果支持微软的文件下载方式(ie10浏览器)if(window。navigator。msSaveBlob){try{constblobObjectnewBlob(〔res。data〕);window。navigator。msSaveBlob(blobObject,fileNamesuffix);}catch(e){console。log(e);}}else{其他浏览器leturlwindow。URL。createObjectURL(res。data)letlinkdocument。createElement(a)link。style。displaynonelink。hrefurllink。setAttribute(download,fileNamesuffix)document。body。appendChild(link)link。click()document。body。removeChild(link)window。URL。revokeObjectURL(link。href);}})。catch((err){console。log(err。message);})}
使用:downloadFile(apidownload,{id},文件名)17、时间操作
关于时间操作,没必要自己再写一大串代码了,强烈推荐使用day。js〔2〕
Day。js是一个仅2kb大小的轻量级JavaScript时间日期处理库,下载、解析和执行的JavaScript更少,为代码留下更多的时间。18、深拷贝exportconstcloneparent{判断类型constisType(obj,type){if(typeofobj!object)returnfalse;consttypeStringObject。prototype。toString。call(obj);letflag;switch(type){caseArray:flagtypeString〔objectArray〕;break;caseDate:flagtypeString〔objectDate〕;break;caseRegExp:flagtypeString〔objectRegExp〕;break;default:flagfalse;}returnflag;};处理正则constgetRegExpre{varflags;if(re。global)flagsg;if(re。ignoreCase)flagsi;if(re。multiline)flagsm;returnflags;};维护两个储存循环引用的数组constparents〔〕;constchildren〔〕;constcloneparent{if(parentnull)returnnull;if(typeofparent!object)returnparent;letchild,proto;if(isType(parent,Array)){对数组做特殊处理child〔〕;}elseif(isType(parent,RegExp)){对正则对象做特殊处理childnewRegExp(parent。source,getRegExp(parent));if(parent。lastIndex)child。lastIndexparent。lastIndex;}elseif(isType(parent,Date)){对Date对象做特殊处理childnewDate(parent。getTime());}else{处理对象原型protoObject。getPrototypeOf(parent);利用Object。create切断原型链childObject。create(proto);}处理循环引用constindexparents。indexOf(parent);if(index!1){如果父数组存在本对象,说明之前已经被引用过,直接返回此对象returnchildren〔index〕;}parents。push(parent);children。push(child);for(letiinparent){递归child〔i〕clone(parent〔i〕);}returnchild;};returnclone(parent);};
此方法存在一定局限性:一些特殊情况没有处理:例如Buffer对象、Promise、Set、Map。
如果确实想要完备的深拷贝,推荐使用lodash中的cloneDeep方法。19、模糊搜索
参数:list原数组keyWord查询的关键词attribute数组需要检索属性exportconstfuzzyQuery(list,keyWord,attributename){constregnewRegExp(keyWord)constarr〔〕for(leti0;ilist。length;i){if(reg。test(list〔i〕〔attribute〕)){arr。push(list〔i〕)}}returnarr}
示例:constlist〔{id:1,name:树哥},{id:2,name:黄老爷},{id:3,name:张麻子},{id:4,name:汤师爷},{id:5,name:胡万},{id:6,name:花姐},{id:7,name:小梅}〕fuzzyQuery(list,树,name)〔{id:1,name:树哥}〕20、遍历树节点exportconstforeachTree(data,callback,childrenNamechildren){for(leti0;idata。length;i){callback(data〔i〕)if(data〔i〕〔childrenName〕data〔i〕〔childrenName〕。length0){foreachTree(data〔i〕〔childrenName〕,callback,childrenName)}}}
示例:
假设我们要从树状结构数据中查找id为9的节点consttreeData〔{id:1,label:一级1,children:〔{id:4,label:二级11,children:〔{id:9,label:三级111},{id:10,label:三级112}〕}〕},{id:2,label:一级2,children:〔{id:5,label:二级21},{id:6,label:二级22}〕},{id:3,label:一级3,children:〔{id:7,label:二级31},{id:8,label:二级32}〕}〕,letresultforeachTree(data,(item){if(item。id9){resultitem}})console。log(result,result){id:9,label:三级111}
中原四大名刹民权白云寺白云寺坐落于商丘市民权县城西南地区20公里外的白云寺村。它与白马寺登封少林寺和开封相国寺被称作中原四大名刹。白云寺建于唐贞观年间(627649年),本名白衣庵。据传每到夏秋季节便云
山东的一个镇,名字独一无二,还是中国罐头第一镇旅游风物志,揽四海胜景,博人间风华。山东省是我国农业大省,特别是沂蒙山区,盛产优质农产品,下面要说的这个镇,位于沂蒙山区腹地,名字非常独特,就叫地方镇,还是中国罐头第一镇,不知道是
盐津网红打卡点东风大桥盐津东风大桥建于上世纪50年代末,是滇东北通往川南地区的唯一通道上的一座雄伟壮观的石拱桥。上图是古老的盐井渡它横跨关河大峡谷东西岸,像一道彩虹降落人间,默默的为滇川人民做着不朽的贡
2022冬季新疆旅游复苏,这些冰雪项目,将会在冬季形成一股热潮新疆,一个拥有雪山花海草原湖泊森林公路雅丹地貌和民族风情浓郁的热土,在这里,可以满足你对新疆旅游的所有想象。但是,随着三年疫情的到来,从2020年开始,新疆旅游一直处于低迷的状态,
乌鲁木齐到底是一座怎样的城市?我在这里待了快十年了。在我眼里,某种程度上,乌鲁木齐就是新疆,新疆就是乌鲁木齐。乌鲁木齐到底是一座怎样的城市?我突然想到王朔小说过把瘾就死里面一个桥段两个人在一起发生了一些事,就像
关于这个季节,它们有话说秋末冬初冬天慢慢向我们靠近万物都蒙上一层寒意但在嘉定的街头巷尾它们的身影,依旧热烈胜辛北路说银杏的金黄是我在这个季节独有的肤色。叶城路说夕阳洒在梧桐大道,满地落叶蕴藏着许多回忆。城
鸡鸣驿,中国保存最完整的明朝驿站,最大的驿站,最小的城京张古道是扼守京西咽喉,通往西北边陲的必经之地,先秦时就以上谷干道而闻名于世,这条千年古道上有很多城镇驿站,而最大的要数鸡鸣驿古城。鸡鸣驿古城位于河北张家口怀来县的鸡鸣山下,始建于
头条每日一游五大道亲爱的友友,您好。今天我们继续游览天津,看看天津特有名气的五大道。光听这地名,就够玄乎的吧。咱们就看看为啥叫五大道?有啥特色吧!五大道位于天津市中心城区,是一个以由南向北并列着的马
黑板报大温亲子周末!糖果节来袭!各种精彩圣诞活动不能错过周二的一场大雪让整个温哥华陷入了混乱!天气预报显示,周五还将有一场大雪。不过,周末将是艳阳高照的天气!皑皑白雪给这个世界又添了一份圣诞的气氛!这个周末,趁着阳光,趁着银装素裹的美丽
因为一个人爱上一座城陪你一起逛过巴扎的人,如今还留在这座城市吗?乌鲁木齐二道桥巴扎三更半夜喝二两小酒,清早八点吃一碗小牛肉面。趁着月光逛二道桥,望望巴扎高耸的砖塔。以前那杯三炮台再泯。现在这杯散伙酒难
黑夜已过,黎明将来,老妖解读旅游业太阳即将升起的时候大家好我是老妖,院部促进消费20条已经出台了10天了,还是陷入了以往政策的怪圈,执行不力有的地方宁愿犯小错,也不愿冒更大的风险,所以继续层层叠加。还好总会有人耐不住寂寞,石家庄打了