11个对开发有帮助的JS技巧。本文已收录到GitHubhttps://github.com/qq449245884/xiaozhi,里面有完整的测试站点、资料和我的一线厂商访谈系列文章。1.生成一个带有随机数的列表Array.from({length:1000},Math.random)//[0.6163093133259432,?0.8877401276499153,?0.4094354756035987,?...]-1000items2.生成一个包含数字的列表from({length:1000},(v,i)=>i)//[0,1,2,3,4,5,6....999]3。RGB→转换为十六进制constrgb2hex=([r,g,b])=>`#${(1<<24)+(r<<16)+(g<<8)+b}`.toString(16).substr(1);rgb2hex([76,11,181]);//#4c0bb54。转换十六进制→RGB如何转换回来?这是实现该目标的好方法。consthex2rgb=hex=>[1,3,5].map((h)=>parseInt(hex.substring(h,h+2),16));hex2rgb("#4c0bb5");//[76,11,181]5。奇数或偶数使用位运算:constvalue=232;if(value&1)console.log("odd");elseconsole.log("even");//even6.检查有效的URLconstisValidURL=(url)=>{try{newURL(url);返回真;}赶上(错误){返回错误;}}isValidURL('https://segmentfault.com/u/minnanitkong/articles')//trueisValidURL("https//invalidto");//false7.从过去到现在的时间表明,有时我们需要打印6分钟前的日期,但我们不想让大型库来做。这是一个小片段:constfromAgo=(date)=>{constms=Date.now()-date.getTime();constseconds=Math.round(ms/1000);const分钟=Math.round(ms/60000);consthours=Math.round(ms/3600000);constdays=Math.round(ms/86400000);constmonths=Math.round(ms/2592000000);constyears=Math.round(ms/31104000000);开关(真){caseseconds<60:return`${seconds}second(s)ago"`;caseminutes<60:return`${minutes}minute(s)ago"`;casehours<24:return`${hours}hour(s)ago"`;casedays<30:return`${days}day(s)ago`;casemonths<12:return`${months}month(s)ago`;默认值:返回`${years}year(s)ago`;}};constcreatedAt=newDate(2021,0,5);fromAgo(createdAt);//14天前;8.生成带参数的路由我们在处理路由/路径时做了很多工作,我们总是需要操作它们。generatePath可以在我们需要生成带参数的路径时帮助我们将浏览器推送到那里!constgeneratePath=(path,obj)=>path.replace(/(:[a-z]+)/g,(v)=>obj[v.substr(1)]);constroute="/app/:page/:id";generatePath(route,{page:"products",id:85,});///应用程序/产品/1239。从路由获取参数constgetPathParams=(path,pathMap,serializer)=>{path=path.split("/");pathMap=pathMap.split("/");returnpathMap.reduce((acc,crr,i)=>{if(crr[0]===":"){constparam=crr.substr(1);acc[param]=serializer&&serializer[param]?serializer[param](path[i]):path[i];}returnacc;},{});};getPathParams("/app/products/123","/app/:page/:id");//{page:'products',id:'123'}getPathParams("/items/2/id/8583212","/items/:category/id/:id",{category:v=>['Car','Mobile','Home'][v],id:v=>+v});//{类别:“家”,编号:858321210.使用查询字符串生成路径constgetQueryParams=url=>url.match(/([^?=&]+)(=([^&]*))/g).reduce((total,crr)=>{const[key,value]=crr.split("=");total[key]=value;returntotal;},{});getQueryParams("/user?name=Orkhan&age=30");//{name:'Orkhan',age:'30'}我是小智,我去洗碗了,下次见~代码部署后可能存在的bug我们无从知晓。事后为了解决这些bug,花了很多时间在日志调试上。顺便推荐一个好用的BUG监控工具,Fundebug。移步天下】尽快阅读,回复【福利】还有很多前端视频等着你,本文已经收录到GitHubhttps://github.com/qq449245884/xiaozhi,欢迎关注星星。
