JavaScript常用工具函数库汇总
对象或数组的深拷贝
/** *对象或数组的深拷贝 *@param{*}cloneObj被克隆的对象 *@param{*}targetObj克隆的目标对象 *@param{*}isOverride若属性重复,是否覆盖被克隆对象的属性 */ functiondeepClone(cloneObj,targetObj,isOverride=true){ const_toString=Object.prototype.toString if(_toString.call(cloneObj)!=='[objectArray]'&&_toString.call(cloneObj)!=='[objectObject]'){ returncloneObj } varcloneTarget=_toString.call(cloneObj)==='[objectArray]'?[]:{} for(letkeyincloneObj){ if(Object.prototype.hasOwnProperty.call(cloneObj,key)){ if(_toString.call(cloneObj[key])==='[objectArray]'||_toString.call(cloneObj[key])==='[objectObject]'){ cloneTarget[key]=deepClone(cloneObj[key]) }else{ cloneTarget[key]=cloneObj[key] } } } if(targetObj&&(_toString.call(cloneObj)===_toString.call(targetObj))){ //这里要注意,克隆的目标对象也要deepClone下 cloneTarget=isOverride ?Object.assign(cloneTarget,deepClone(targetObj)) :Object.assign(deepClone(targetObj),cloneTarget) } returncloneTarget }
精准判断数据类型
//精准判断数据类型 functiongetVerifyDataTypes(){ consttypes=["String","Number","Boolean","Null","Undefined","Function","Object","Array","Date","Error","RegExp","Symbol","Map","Set"] letType={} //示例用法:Type.isString('javascript') for(leti=0;iObject.prototype.toString.call(obj)===`[object${types[i]}]` } //判断字符串是否为json格式 Type.isJsonStr=str=>{ if(typeofstr=='string'){ try{ letobj=JSON.parse(str); if(obj&&typeofobj=='object'){ returntrue; } returnfalse; }catch(e){ returnfalse; } }else{ returnfalse; } } returnType }
日期格式化
/** *日期格式化 *@param{*}date日期对象 *@param{*}beforeHyphen年月日连字符 *@param{*}afterHyphen时分秒连字符 */ functionformatDate(date=newDate(),beforeHyphen='-',afterHyphen=':'){ constformatNumber=n=>{ n=n.toString() returnn[1]?n:`0${n}` } constyear=date.getFullYear() constmonth=date.getMonth()+1 constday=date.getDate() consthour=date.getHours() constminute=date.getMinutes() constsecond=date.getSeconds() constymd=[year,month,day].map(formatNumber).join(beforeHyphen) consthms=[hour,minute,second].map(formatNumber).join(afterHyphen) return`${ymd}${hms}` }
把时间戳转换为剩余的天、时、分、秒
/** *把时间戳转换为剩余的天、时、分、秒,一般应用于倒计时场景中 *@param{*}timestamp时间戳 */ functionconverTimestamp(timestamp){ constformatNumber=n=>{ n=n.toString() returnn[1]?n:`0${n}` } letday=Math.floor((timestamp/1000/3600)/24); lethour=Math.floor((timestamp/1000/3600)%24); letminute=Math.floor((timestamp/1000/60)%60); letsecond=Math.floor(timestamp/1000%60); return{ day:day, hour:formatNumber(hour), minute:formatNumber(minute), second:formatNumber(second) } }
从数组中随机取出一项
//从数组中随机取出一项 functiongetRandomItemByArray(items){ returnitems[Math.floor(Math.random()*items.length)]; }
将有父子关系的数组转换成树形结构数据
letdata=[ {parentId:0,id:1,value:'xxx'}, {parentId:1,id:3,value:'xxx'}, {parentId:4,id:6,value:'xxx'}, {parentId:3,id:5,value:'xxx'}, {parentId:2,id:4,value:'xxx'}, {parentId:1,id:2,value:'xxx'}, ] //转换为树形Array结构 functiontoTreeAry(arr,pId=0){ returnarr .filter(({parentId})=>parentId===pId) .map(a=>({ ...a, children:toTreeAry(arr.filter(({parentId})=>parentId!==pId),a.id) })) } //转换为树形Object结构 functiontoTreeObj(arr,pId=0){ letres={} arr.filter(({parentId})=>parentId===pId) .forEach(a=>{ res[a.id]={ ...a, children:toTreeObj(arr.filter(({parentId})=>parentId!==pId),a.id) } }) returnres } console.log(toTreeAry(data)) console.log(toTreeObj(data))
生成随机字符串
//随机字符串 constrandomStr=()=>{ returnnewDate().getTime()+'-'+Math.random().toString(36).substr(2) }
过滤html标签
//过滤html标签 constfilterHTMLTag=(str)=>{ str=str.replace(/<\/?[^>]*>/g,'');//去除HTMLTag str=str.replace(/[|]*\n/,'')//去除行尾空格 str=str.replace(/&npsp;/ig,'');//去掉npsp returnstr; }
以上就是JavaScript常用工具函数库汇总的详细内容,更多关于JavaScript工具函数库的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。