缓存相关
获取指定 Cookie 值
export const getCookie = (k) => { const res = RegExp('(^|; )' + encodeURIComponent(k) + '=([^;]*)').exec(document.cookie) return res && res[2] }
设置 Cookie 值
export function setCookie(name, value, expriesDays, encode = false) { var Days = expriesDays || 10 var exp = new Date() exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000) const val = encode ? escape(value) : value document.cookie = name + '=' + val + ';domain=zhuanzhuan.com;path=/;expires=' + exp.toUTCString() }
简易版 Storage 操作,sessionStorage 及 localStorage 类似
const prefix = '_XXX_' export function getStorage(key) { const content = sessionStorage.getItem(`${prefix}${key}`) if (content) { try { const params = JSON.parse(content) const expires = params.expires // 未设置过期 及 未过期 if (!expires || (expires && Date.now() <= expires)) { return params.data } } catch (e) { console.log(e) } } } export function setStorage(key, data = {}, expires) { try { const params = { data } if (expires) { params.expires = expires } sessionStorage.setItem(`${prefix}${key}`, JSON.stringify(params)) } catch (e) { console.log(e) } }
数字相关
数字四舍五入,保留n位小数
export function round(number, n) { n = n ? parseInt(n) : 0 if (n <= 0) return Math.round(number) number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n) return number }
数字每千位加逗号
export function toThousands(num) { return num && num.toString() .replace(/\d+/, function(s){ return s.replace(/(\d)(?=(\d{3})+$)/g, '$1,') }) }
随机数
export function random(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) }
字符串相关
手机号码中间4位隐藏星号
export function hideMobile(mobile) { return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2") }
检测密码强度 1:密码弱 2:密码中等 3:密码强 4:密码很强
export function checkPassWord(str) { let level = 0; if (str.length < 6) { return level }; if (/[0-9]/.test(str)) { level++ }; if (/[a-z]/.test(str)) { level++ }; if (/[A-Z]/.test(str)) { level++ }; if(/\W/.test(str)){ level++ } return level }
随机产生某个颜色
export function randomColor() { return `rgb(${this.random(0, 255)}, ${this.random(0, 255)}, ${this.random(0, 255)})` }
字符串替换全部
export function replaceAll(s0, s1, s2){ return s0.replace(new RegExp(s1, "gm"), s2); }
版本号比较
传入两个版本号,格式如:4.3.2,返回结果,小于-1,等于0,大于1。
export function compareVersion(v1, v2) { var s1 = v1.split(".").map(v => parseInt(v)); var s2 = v2.split(".").map(v => parseInt(v)); var len1 = s1.length, len2 = s2.length, commonLen = Math.min(len1, len2); for (var i = 0; i < commonLen; ++i) { if (seq1[i] != seq2[i]) return seq1[i]<seq2[i] ? -1 : 1; } return len1 === len2 ? 0 : (len1 < len2 ? -1 : 1); }
对象转url字符串供导出接口(GET)使用
const objectToQueryString = (paramObj) => { const tmpArray = [] // 特殊字符转义 const filter = (str) => { str += '' // 隐式转换 str = str.replace(/%/g, '%25') str = str.replace(/\+/g, '%2B') str = str.replace(/ /g, '%20') str = str.replace(/\//g, '%2F') str = str.replace(/\?/g, '%3F') str = str.replace(/&/g, '%26') str = str.replace(/\=/g, '%3D') str = str.replace(/#/g, '%23') return str } for (const attr in paramObj) { tmpArray.push(`${attr}=${filter(paramObj[attr])}`) } return tmpArray.join('&') }
其他
函数防抖
export function debounce(fn, delay) { delay = delay || 1000; let timer = null; return function () { let context = this; let arg = arguments; if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(context, arg); }, delay); }; }
节流函数
export function throttle(fn, delay = 300) { let timer = null; return function () { let context = this; let args = arguments; if (!timer) { timer = setTimeout(function () { fn.apply(context, args); clearTimeout(timer); }, delay); } }; }
最后
除开本文所示的场景,也还有很多没有列举到的情况,如果你有认为很不错的工具函数,欢迎留言交流~