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

5个实用的JS库99%可能不知道

时间:2023-03-15 23:08:25 科技观察

前言作为一名前端开发者,我通过这些JavaScript库大大提高了自己的效率,比如格式化日期、处理URL参数、调试手机网页等。因此,我想把这些有用的库分享给大家,希望对大家有所帮助。1.使用“Day.js”格式化日期和时间地址:https://day.js.org/en/作为开发者,我厌倦了在JavaScript中操作日期和时间,因为它很麻烦。比如我们要打印当前的日期和时间,就需要写一大段代码才能完成。constgetDate=()=>{constfillZero=(t)=>{返回t<10?`0${t}`:t}constd=newDate()constyear=d.getFullYear()constmonth=fillZero(d.getMonth()+1)constday=fillZero(d.getDate())consthour=fillZero(d.getHours())constminute=fillZero(d.getMinutes())constsecond=fillZero(d.getSeconds())返回`${year}-${month}-${day}${hour}:${minute}:${second}`}console.log(getDate())//2022-05-0907:19:14幸运的是,使用Day.js只需一行代码即可完成.console.log(dayjs().format('YYYY-MM-DDHH:mm:ss'))//2022-05-0907:19:14注意:“Day.js是一个极简的JavaScript库,它解析,验证、操作和显示现代浏览器的日期和时间,使用大多数与Moment.js兼容的API。如果你使用过Moment.js,你也不会发现使用Day.js有困难。》2、使用“qs.js”格式化url参数地址:https://github.com/ljharb/qs为了获取“url”的参数,我们可能会写这样一个函数constformatSearch=()=>{window.location.search.slice(1).split('&').reduce((res,it)=>{const[key,value]=it.split('=')res[key]=valuereturnres},{})}//https://medium.com?name=fatfish&age=100constsearch=formatSearch()//{name:'fatfish',age:100}//使用qs.js来formatconstsearch2=qs.parse(window.location.search.slice(1))//{name:'fatfish',age:100}但是,如果我们现在要实现这样一个新功能,就会变得容易得多。如果我们想在“https://medium.com”中添加name和age两个参数。//1.url=https://medium.com//2.params={name:'fatfish',age:100}constsplitSearch=(url,params)=>constsearch=Object.entries(params).map((it)=>it.join('=')).join('&')返回`${url}?${search}`}consturl='https://medium.com'constparams={name:'fatfish',age:100}console.log(splitSearch(url,params))//https://medium.com?name=fatfish&age=100//使用qs.js将urlconsole.log(`${url}?${qs.stringify(params)}`)//https://medium.com?name=fatfish&age=1003。使用“js-cookie.js”读写cookie地址:https://github.com/js-cookie/js-cookie大家都知道在JavaScript中操作cookie不是一件简单的事情,为了提高自己的工作效率我强烈推荐“js-cookie.js”,它是一个简单、轻量级的处理cookies的JavaScriptAPI。//1.url=https://medium.com//2.params={name:'fatfish',age:100}constsplitSearch=(url,params)=>{constsearch=Object.entries(params).map((it)=>it.join('=')).join('&')返回`${url}?${search}`}consturl='https://medium.com'constparams={name:'fatfish',age:100}console.log(splitSearch(url,params))//https://medium.com?name=fatfish&age=100//使用qs.js对urlconsole.log进行字符串化(`${url}?${qs.stringify(params)}`)//https://medium.com?name=fatfish&age=1004。为什么选择Lodash?地址:https://github.com/lodash/lodash先来看一下Lodash的介绍:Lodash通过消除处理数组、数字、对象、字符串等的麻烦,让JavaScript变得更简单。Lodash的模块化方法非常适合:遍历数组、对象和字符串操作以及测试值以创建复合函数//1.展平数组_.flattenDeep([1,[2,[3,[4,[5]]]]])//[1,2,3,4,5]//2.更方便的对象遍历_.each({name:'fatfish',age:100},(val,key)=>{console.log(val,key)//fatfishname//100'age'})//3....5.移动端使用“Vconsole”调试网页地址:https://github.com/Tencent/vConsole移动端在线调试网页非常困难,但是有了“Vconsole”,一切都会简单很多。TIP:与chrome浏览器的devtools类似,Vconsole提供了以下功能帮助你更好的调试网页。Log:console.log,info,error,...Network:XMLHttpRequest,Fetch,sendBeaconElement:HTML元素树Storage:Cookies,LocalStorage,SessionStorage手动执行JS命令自定义插件