




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
第JavaScript常用的工具函數(shù)分享目錄格式化時間戳時間格式化幾分鐘前幾小時前url參數(shù)轉(zhuǎn)為對象對象序列化【對象轉(zhuǎn)url參數(shù)】本地存儲cookie操作數(shù)字格式化單位數(shù)字千位過濾過濾成版本號首字母大寫class操作文本復(fù)制功能判斷是否是一個數(shù)組判斷是否是一個空數(shù)組克隆一個數(shù)組數(shù)組去重是否為PC端判斷是否為微信設(shè)備判斷:android、ios、web常見正則校驗去除字符串空格過濾html代碼生成隨機數(shù)范圍判斷圖片加載完成光標所在位置插入字符圖片地址轉(zhuǎn)base64base64圖片下載功能瀏覽器是否支持webP格式圖片H5軟鍵盤縮回、彈起回調(diào)對象屬性剔除深拷貝函數(shù)防抖函數(shù)節(jié)流前言;
JavaScript(JS)是一種具有函數(shù)優(yōu)先的輕量級,解釋型或即時編譯型的編程語言。雖然它是作為開發(fā)Web頁面的腳本語言而出名的,但是它也被用到了很多非瀏覽器環(huán)境中等等。
格式化時間戳
exportfunctionformatDateTimeStamp(date,fmt){
//格式化時間戳:formatDateTimeStamp(newDate(time),'yyyy-MM-ddhh:mm:ss')
if(/(y+)/.test(fmt)){
fmt=fmt.replace(RegExp.$1,(date.getFullYear()+'').substr(4-RegExp.$1.length))
}
leto={
'M+':date.getMonth()+1,
'd+':date.getDate(),
'h+':date.getHours(),
'm+':date.getMinutes(),
's+':date.getSeconds()
}
for(letkino){
if(newRegExp(`(${k})`).test(fmt)){
letstr=o[k]+''
fmt=fmt.replace(
RegExp.$1,(RegExp.$1.length===1)
str:
padLeftZero(str))
}
}
returnfmt
functionpadLeftZero(str){
return('00'+str).substr(str.length);
exportfunctionparseTime(time,cFormat){
if(arguments.length===0){
returnnull
}
constformat=cFormat||'{y}-{m}-or2p3ii{h}:{i}:{s}'
letdate
if(typeoftime==='object'){
date=time
}else{
if((typeoftime==='string')(/^[0-9]+$/.test(time))){
time=parseInt(time)
}
if((typeoftime==='number')(time.toString().length===10)){
time=time*1000
}
date=newDate(time)
}
constformatObj={
y:date.getFullYear(),
m:date.getMonth()+1,
d:date.getDate(),
h:date.getHours(),
i:date.getMinutes(),
s:date.getSeconds(),
a:date.getDay()
}
consttime_str=format.replace(/{([ymdhisa])+}/g,(result,key)={
constvalue=formatObj[key]
//Note:getDay()returns0onSunday
if(key==='a'){
return['日','一','二','三','四','五','六'][value]
}
returnvalue.toString().padStart(2,'0')
})
returntime_str
}
時間格式化幾分鐘前幾小時前
exportfunctionformatTime(time,option){
if((''+time).length===10){
time=parseInt(time)*1000
}else{
time=+time
}
constd=newDate(time)
constnow=Date.now()
constdiff=(now-d)/1000
if(diff30){
return'剛剛'
}elseif(diff3600){
//less1hour
returnMath.ceil(diff/60)+'分鐘前'
}elseif(diff3600*24){
returnMath.ceil(diff/3600)+'小時前'
}elseif(diff3600*24*2){
return'1天前'
}
if(option){
returnparseTime(time,option)
}else{
return(
d.getMonth()+
1+
'月'+
d.getDate()+
'日'+
d.getHours()+
'時'+
d.getMinutes()+
'分'
)
}
functionpluralize(time,label){
if(time===1){
returntime+label+'ago'
}
returntime+label+'s'+'ago'
exportfunctiontimeAgo(time){
constbetween=Date.now()/1000-Number(time)
if(between3600){
returnpluralize(~~(between/60),'minute')
}elseif(between86400){
returnpluralize(~~(between/3600),'hour')
}else{
returnpluralize(~~(between/86400),'day')
}
}
url參數(shù)轉(zhuǎn)為對象
exportfunctiongetQueryObject(url){
url=url==nullwindow.location.href:url
constsearch=url.substring(url.lastIndexOf('')+1)
constobj={}
constreg=/([^=]+)=([^=]*)/g
search.replace(reg,(rs,$1,$2)={
constname=decodeURIComponent($1)
letval=decodeURIComponent($2)
val=String(val)
obj[name]=val
returnrs
})
returnobj
exportfunctionparam2Obj(url){
constsearch=url.split('')[1]
if(!search){
return{}
}
returnJSON.parse(
'{"'+
decodeURIComponent(search)
.replace(/"/g,'\\"')
.replace(//g,'","')
.replace(/=/g,'":"')
.replace(/\+/g,'')+
'"}'
)
}
對象序列化【對象轉(zhuǎn)url參數(shù)】
functioncleanArray(actual){
constnewArray=[]
for(leti=0;iactual.length;i++){
if(actual[i]){
newArray.push(actual[i])
}
}
returnnewArray
exportfunctionparam(obj){
if(!obj)return''
returncleanArray(
Object.keys(obj).map(key={
if(obj[key]===undefined)return''
returnencodeURIComponent(key)+'='+encodeURIComponent(obj[key])
})
).join('')
exportfunctionstringfyQueryStr(obj){
if(!obj)return'';
letpairs=[];
for(letkeyinobj){
letvalue=obj[key];
if(valueinstanceofArray){
for(leti=0;ivalue.length;++i){
pairs.push(encodeURIComponent(key+'['+i+']')+'='+encodeURIComponent(value[i]));
}
continue;`在這里插入代碼片`
}
pairs.push(encodeURIComponent(key)+'='+encodeURIComponent(obj[key]));
}
returnpairs.join('
param({name:'1111',sex:'wwww'})
stringfyQueryStr({name:'1111',sex:'wwww'})
本地存儲
exportconststore={//本地存儲
set:function(name,value,day){//設(shè)置
letd=newDate()
lettime=0
day=(typeof(day)==='undefined'||!day)1:day//時間,默認存儲1天
time=d.setHours(d.getHours()+(24*day))//毫秒
localStorage.setItem(name,JSON.stringify({
data:value,
time:time
}))
},
get:function(name){//獲取
letdata=localStorage.getItem(name)
if(!data){
returnnull
}
letobj=JSON.parse(data)
if(newDate().getTime()obj.time){//過期
localStorage.removeItem(name)
returnnull
}else{
returnobj.data
}
},
clear:function(name){//清空
if(name){//刪除鍵為name的緩存
localStorage.removeItem(name)
}else{//清空全部
localStorage.clear()
}
}
}
cookie操作
exportconstcookie={//cookie操作【set,get,del】
set:function(name,value,day){
letoDate=newDate()
oDate.setDate(oDate.getDate()+(day||30))
document.cookie=name+'='+value+';expires='+oDate+";path=/;"
},
get:function(name){
letstr=document.cookie
letarr=str.split(';')
for(leti=0;iarr.length;i++){
letnewArr=arr[i].split('=')
if(newArr[0]===name){
returnnewArr[1]
}
}
},
del:function(name){
this.set(name,'',-1)
}
}
數(shù)字格式化單位
exportfunctionnumberFormatter(num,digits)
constsi=[{
value:1E18,
symbol:'E'
},
{
value:1E15,
symbol:'P'
},
{
value:1E12,
symbol:'T'
},
{
value:1E9,
symbol:'G'
},
{
value:1E6,
symbol:'M'
},
{
value:1E3,
symbol:'k'
}
]
for(leti=0;isi.length;i++){
if(num=si[i].value){
return(num/si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/,'$1')+si[i].symbol
}
}
returnnum.toString()
}
數(shù)字千位過濾
exportfunctiontoThousandFilter(num){
lettargetNum=(num||0).toString()
if(targetNum.includes('.')){
letarr=num.split('.')
returnarr[0].replace(/^-\d+/g,m=m.replace(/(=(!\b)(\d{3})+$)/g,','))+'.'+arr[1]
}else{
returntargetNum.replace(/^-\d+/g,m=m.replace(/(=(!\b)(\d{3})+$)/g,','))
}
}
過濾成版本號
exportfunctionversionFilter(versions){
letv0=(versions0xff000000)24
letv1=(versions0xff0000)16
letv2=(versions0xff00)8
letv3=versions0xff
return`${v0}.${v1}.${v2}.${v3}`
}
首字母大寫
exportfunctionuppercaseFirst(string){
returnstring.charAt(0).toUpperCase()+string.slice(1)
}
class操作
exportfunctionhasClass(ele,cls){
return!!ele.className.match(newRegExp('(\\s|^)'+cls+'(\\s|$)'))
exportfunctionaddClass(ele,cls){
if(!hasClass(ele,cls))ele.className+=''+cls
exportfunctionremoveClass(ele,cls){
if(hasClass(ele,cls)){
constreg=newRegExp('(\\s|^)'+cls+'(\\s|$)')
ele.className=ele.className.replace(reg,'')
}
}
文本復(fù)制功能
constcopyTxt=function(text,fn){//復(fù)制功能
if(typeofdocument.execCommand!=='function'){
console.log('復(fù)制失敗,請長按復(fù)制')
return
}
vardom=document.createElement('textarea')
dom.value=text
dom.setAttribute('style','display:block;width:1px;height:1px;')
document.body.appendChild(dom)
dom.select()
varresult=document.execCommand('copy')
document.body.removeChild(dom)
if(result){
console.log('復(fù)制成功')
typeoffn==='function'fn()
return
}
if(typeofdocument.createRange!=='function'){
console.log('復(fù)制失敗,請長按復(fù)制')
return
}
varrange=document.createRange()
vardiv=document.createElement('div')
div.innerhtml=text
div.setAttribute('style','height:1px;fontSize:1px;overflow:hidden;')
document.body.appendChild(div)
range.selectNode(div)
varselection=window.getSelection()
console.log(selection)
if(selection.rangeCount0){
selection.removeAllRanges()
}
selection.addRange(range)
document.execCommand('copy')
typeoffn==='function'fn()
console.log('復(fù)制成功')
}
判斷是否是一個數(shù)組
exportconstcastArray=value=(Array.isArray(value)value:[value])
exportconstcastArray=arr=
Ototype.toString.call(arr)==='[objectArray]'
判斷是否是一個空數(shù)組
exportconstisEmpty=(arr)=!Array.isArray(arr)||arr.length===0
克隆一個數(shù)組
/**
*@param{Array}arr
constclone=(arr)=arr.slice(0);
//Or
constclone=(arr)=[...arr];
//Or
constclone=(arr)=Array.from(arr);
//Or
constclone=(arr)=arr.map((x)=
//Or
constclone=(arr)=JSON.parse(JSON.stringify(arr));
//Or
constclone=(arr)=arr.concat([]);
數(shù)組去重
/**
*@param{Array}arr
*@returns{Array}
exportconstuniqueArray=(arr)=Array.from(newSet(arr))
//Or
exportconstuniqueArray=(arr)=arr.filter((el,i,array)=array.indexOf(el)===i)
//Or
exportconstuniqueArray=(arr)=arr.reduce((acc,el)=(acc.includes(el)acc:[...acc,el]),[])
是否為PC端
exportconstisPC=function(){//是否為PC端
letuserAgentInfo=navigator.userAgent
letAgents=['Android','iPhone','SymbianOS','WindowsPhone','iPad','iPod']
letflag=true
for(letv=0;vAgents.length;v++){
if(userAgentInfo.indexOf(Agents[v])0){
flag=false
break
}
}
returnflag
}
判斷是否為微信
exportconstisWx=()={//判斷是否為微信
varua=window.navigator.userAgent.toLowerCase()
if(ua.match(/MicroMessenger/i)==='micromessenger'){
returntrue
}
returnfalse
}
設(shè)備判斷:android、ios、web
exportconstisDevice=function(){//判斷是android還是ios還是web
varua=navigator.userAgent.toLowerCase()
if(ua.match(/iPhone\sOS/i)==='iphoneos'||ua.match(/iPad/i)==='ipad'){//ios
return'iOS'
}
if(ua.match(/Android/i)==='android'){
return'Android'
}
return'Web'
}
常見正則校驗
/*正則匹配*/
exportconstnormalReg=(str,type)={
switch(type){
case'phone':
//手機號碼
return/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
case'tel':
//座機
return/^(0\d{2,3}-\d{7,8})(-\d{1,4})$/.test(str);
case'card':
//身份證
return/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
case'pwd':
//密碼以字母開頭,長度在6~18之間,只能包含字母、數(shù)字和下劃線
return/^[a-zA-Z]\w{5,17}$/.test(str)
case'postal':
//郵政編碼
return/[1-9]\d{5}(!\d)/.test(str);
case'QQ':
//QQ號
return/^[1-9][0-9]{4,9}$/.test(str);
case'email':
//郵箱
return/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case'money':
//金額(小數(shù)點2位)
return/^\d*(:\.\d{0,2})$/.test(str);
case'URL':
//網(wǎng)址
return/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@^=%:/~\+#]*[\w\-\@^=%/~\+#])/.test(str)
case'IP':
//IP
return/((:(:25[0-5]|2[0-4]\\d|[01]\\d\\d)\\.){3}(:25[0-5]|2[0-4]\\d|[01]\\d\\d))/.test(str);
case'date':
//日期時間
return/^(\d{4})\-(\d{2})\-(\d{2})(\d{2})(:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str)||/^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
case'number':
//數(shù)字
return/^[0-9]$/.test(str);
case'positiveInteger':
//正整數(shù)
return/^[1-9]\d*$/.test(str);
case'price':
//價格
return/(^[1-9]\d*(\.\d{1,2})$)|(^0(\.\d{1,2})$)/.test(str);//價格非0則去掉''
case'english'://英文
return/^[a-zA-Z]+$/.test(str);
case'chinese'://中文
return/^[\u4E00-\u9FA5]+$/.test(str);
case'lower':
//小寫
return/^[a-z]+$/.test(str);
case'upper':
//大寫
return/^[A-Z]+$/.test(str);
case'HTML':
//HTML標記
return/("[^"]*"|'[^']*'|[^'"])*/.test(str);
default:
returntrue;
}
}
去除字符串空格
exportconsttrim=function(str,type){
type=type||1
switch(type){
case1:
returnstr.replace(/\s+/g,'')
case2:
returnstr.replace(/(^\s*)|(\s*$)/g,'')
case3:
returnstr.replace(/(^\s*)/g,'')
case4:
returnstr.replace(/(\s*$)/g,'')
default:
returnstr
}
}
過濾html代碼
exportconstfilterTag=function(str){//過濾html代碼(把轉(zhuǎn)換)
str=str.replace(//ig,'')
str=str.replace(//ig,'')
str=str.replace(//ig,'')
str=str.replace('','')
returnstr
}
生成隨機數(shù)范圍
exportconstrandom=function(min,max){//生成隨機數(shù)范圍
if(arguments.length===2){
returnMath.floor(min+Math.random()*((max+1)-min))
}else{
returnnull
}
}
判斷圖片加載完成
exportconstimgLoadAll=function(arr,callback){//圖片加載
letarrImg=[]
for(leti=0;iarr.length;i++){
letimg=newImage()
img.src=arr[i]
img.onload=function(){
arrImg.push(this)
if(arrImg.length==arr.length){
callbackcallback()
}
}
}
}
光標所在位置插入字符
exportconstinsertAtCursor=function(dom,val){//光標所在位置插入字符
if(document.selection){
dom.focus()
letsel=document.selection.createRange()
sel.text=val
sel.select()
}elseif(dom.selectionStart||dom.selectionStart=='0'){
letstartPos=dom.selectionStart
letendPos=dom.selectionEnd
letrestoreTop=dom.scrollTop
dom.value=dom.value.substring(0,startPos)+val+dom.value.substring(endPos,dom.value.length)
if(restoreTop0){
dom.scrollTop=restoreTop
}
dom.focus()
dom.selectionStart=startPos+val.length
dom.selectionEnd=startPos+val.length
}else{
dom.value+=val
dom.focus()
}
}
圖片地址轉(zhuǎn)base64
exportconstgetBase64=function(img){
//傳入圖片路徑,返回base64,使用getBase64(url).then(function(base64){},function(err){});
letgetBase64Image=function(img,width,height){
//width、height調(diào)用時傳入具體像素值,控制大小,不傳則默認圖像大小
letcanvas=document.createElement("canvas");
canvas.width=widthwidth:img.width;
canvas.height=heightheight:img.height;
letctx=canvas.getContext("2d");
ctx.drawImage(img,0,0,canvas.width,canvas.height);
letdataURL=canvas.toDataURL();
returndataURL;
}
letimage=newImage();
image.crossOrigin='';
image.src=img;
letdeferred=$.Deferred();
if(img){
image.onload=function(){
deferred.resolve(getBase64Image(image));
}
returnmise();
}
}
base64圖片下載功能
exportconstdownloadFile
=(base64,fileName)={
letbase64ToBlob=(code)={
letparts=code.split(';base64,');
letcontentType=parts[0].split(':')[1];
letraw=window.atob(parts[1]);
letrawLength=raw.length;
letuInt8Array=newUint8Array(rawLength);
for(leti=0;irawLength;++i){
uInt8Array[i]=raw.charCodeAt(i);
}
returnnewBlob([uInt8Array],{
type:contentType
});
};
letaLink=document.createElement('a');
letblob=base64ToBlob(base64);//newBlob([content]);
letevt=document.createEvent("HTMLEvents");
evt.initEvent("click",true,true);
//initEvent不加后兩個參數(shù)在FF下會報錯
事件類型,是否冒泡,是否阻止瀏覽器的默認行為
aLink.download=fileName;
aLink.href=URL.createObjectURL(blob);
aLink.click();
}
瀏覽器是否支持webP格式圖片
exportconstwebPBool=()=!![].map
document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp')==0
H5軟鍵盤縮回、彈起回調(diào)
/*當軟件鍵盤彈起會改變當前window.innerHeight
監(jiān)聽這個值變化[downCb當軟鍵盤彈起后,縮回的回調(diào),upCb當軟鍵盤彈起的回調(diào)]*/
exportfunction(downCb,upCb){
varclientHeight=window.innerHeight
downCb=typeofdownCb==='function'downCb:function(){}
upCb=typeofupCb==='function'upCb:function(){}
window.addEventListener('resize',()={
varheight=window.innerHeight
if(height===clientHeight){
downCb()
}
if(heightclientHeight){
upCb()
}
})
}
對象屬性剔除
functionomit(object,props=[]){
letres={}
Object.keys(object).forEach(key={
if(props.includes(key)===false){
res[key]=typeofobject[key]==='object'object[key]!==nulljsON.parse(jsON.stringify(object[key])):object[key]
}
})
returnres
//forexample
letdata={
id:1,
title:'12345',
name:'男'}
omit(data,['id'])
//data---{title:'xxx',name:'男'}
深拷貝
exportfunctiondeepClone(source){
if(!sourcetypeofsource!=='object'){
thrownewError
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 產(chǎn)品支付訂金合同范例
- 修建贊助合同范例
- 600畝土地承包合同樣本
- 三年級作文寫作技巧提升計劃
- 統(tǒng)計學專業(yè)醫(yī)療統(tǒng)計實習總結(jié)
- 班長職責在班級活動中的組織技巧
- 幼兒園財務(wù)室的工作職責與實施
- 農(nóng)業(yè)生產(chǎn)環(huán)境友好型措施與質(zhì)量標準
- 科研單位安全生產(chǎn)管理目標計劃
- 幼兒園心理健康安全防護計劃
- 國開(陜西)2024年秋《社會調(diào)查》形考作業(yè)1-4
- 立式水輪發(fā)電機檢修技術(shù)規(guī)程宣貫課件
- 醫(yī)院重點監(jiān)控藥物的合理應(yīng)用
- 重慶市工程標準-重慶市大樹養(yǎng)護技術(shù)規(guī)程
- 《裝配式建筑用墻板技術(shù)要求》JGT578-2021
- 2024年農(nóng)產(chǎn)品食品檢驗員(三級)職業(yè)鑒定考試題庫(含答案)
- 撥叉加工工藝及夾具設(shè)計畢業(yè)設(shè)計
- 人工智能在新聞中的應(yīng)用
- (高清版)TDT 1015.1-2024 地籍數(shù)據(jù)庫 第1部分:不動產(chǎn)
- 幼小銜接 每日一練
- 哈爾濱市木蘭縣文職輔警招聘考試真題
評論
0/150
提交評論