js常用工具函数
# 获取任意变量的类型
const isType = (param) => {
return typeof param !== "object" ? typeof param : Object.prototype.toString.call(param).slice(8, -1).toLowerCase();
};
# 防抖函数
const debounce = (() => {
let timer = null;
return (callback, wait = 800) => {
timer && clearTimeout(timer);
timer = setTimeout(callback, wait);
};
})();
// 使用
Btn.onclick = () => {
debonce(() => {
console.log("事件触发");
}, 800);
};
# 手机号中间加*
const hideMobile = (mobile) => {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};
# 将页面缓慢的滚动到顶部
const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
};
# 滚动到指定元素位置
const smoothScroll = (element) => {
document.querySelector(element).scrollIntoView({
behavior: "smooth",
});
};
# 金额格式化
const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s = ''
const toFixedFix = function(n, prec) {
const k = Math.pow(10, prec)
return '' + Math.ceil(n * k) / k
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, '$1' + sep + '$2')
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
# 存储操作
class MyCache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setItem(key, value) {
if (typeof (value) === 'object') value = JSON.stringify(value)
this.storage.setItem(key, value)
}
getItem(key) {
try {
return JSON.parse(this.storage.getItem(key))
} catch (err) {
return this.storage.getItem(key)
}
}
removeItem(key) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
key(index) {
return this.storage.key(index)
}
length() {
return this.storage.length
}
}
const localCache = new MyCache()
const sessionCache = new MyCache(false)
export { localCache, sessionCache }
部分工具函数来源:呛再首 https://juejin.cn/post/7132714583399071758
编辑 (opens new window)
上次更新: 2022/09/08, 12:02:51