// 防抖函数,应用场景:避免按钮屡次点击,调整浏览器大小 resize 过于频繁,键盘抬起
const debounce = (()=>{
let timer = null;
return (callback,time=800)=>{timer && clearTimeout(timer)
timer = setTimeout(callback, time);
}
})()
// 应用示例:btn.addEventListener("click",function(){debounce(()=>{XXX 逻辑代码 XX},2000) })
// 节流函数,const throttle = (()=>{
let last = 0;
return (callback,time=800)=>{let now = +new Date()
if(now-last>time){callback();
last = now;
}
}
})()
// 数组对象去重
const uniqueArrayObject = (arr=[],key="id")=>{if(arr.length == 0) return false;
let map = {}
arr.forEach(element => {if(!map[element[key]]){map[element[key]] = element
}
});
return Object.values(map)
}
// 判断数据类型
const typeOf = obj =>Object.prototype.toString.call(obj).slice(8,-1)
// 滚动到页面顶部
const scrollTop = ()=>{
let height = document.documentElement.scrollTop || document.body.scrollTop;
if(height>10){window.requestAnimationFrame(scrollTop)
window.scrollTo(height,height/8)
}
}
// 滚动到固定某一地位
const scrollElement = el=>{document.querySelector(el).scrollIntoView({behavior:'smooth'})
}
// 获取以后工夫
const getTime = (date=new Date())=>{let y = date.getFullYear();
let m = date.getMonth()+1;
m = m<10?'0'+m : m;
let d = date.getDate()
d = d<10? "0"+ d: d;
return y+'/'+m+'/'+d
}
// 获取月份的第一天及最初一天
const getFirstLastDay =()=>{let now = new Date()
let y = now.getFullYear();
let m = now.getMonth();
let firstDay = new Date(y,m,1)
let lastDay = new Date(y,m+1,0)
firstDay = firstDay.getMonth + 1 + '/'+'0'+firstDay.getDate()
lastDay = lastDay.getMonth+1 + '/'+lastDay.getDate();
return {firstDay,lastDay}
}
// 含糊查问
const searchQuery = (list=[],keyword,attr='name')=>{let reg = new RegExp(keyword)
let arr = []
list.forEach(i=>{if(reg.test(i[attr])){arr.push(i)
}
})
return arr;
}
let commonFun = {
debounce,
throttle,
uniqueArrayObject,
typeOf,
scrollTop,
scrollElement,
getTime,
getFirstLastDay,
searchQuery
}
window.commonFun = commonFun