// 防抖函数,使用场景:防止按钮多次点击,调整浏览器大小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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。