1. 数组操作
生成指定范围随机整数
// [min, max]
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2. 数组操作
- 打乱数组
const arrScrambling = (arr) => { for (let i = 0; i < arr.length; i++) { const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i; [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]; } return arr; }
- 随机获取数组中的数
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
3. 字符串操作
- 随机生成字符串:使用0123456789ABCDEF随机生成形如xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxxx的字符串
function creatGUID(){ let arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] let res = [] for(let i = 0;i<32;i++){ let num = Math.floor(Math.random()*16); res.push(arr[num]) } let result = res.slice(0,8).join('')+'-'+res.slice(8,12).join('')+'-'+res.slice(12,16).join('')+'-'+res.slice(16).join('') return result } console.log(creatGUID());
- 字符串首字母大写
const fistLetterUpper = (str) => { return str.charAt(0).toUpperCase() + str.slice(1); };
- 驼峰命名转换成短横线命名
export const getKebabCase = (str) => { return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase()) }
- 短横线命名转换成驼峰命名
export const getCamelCase = (str) => { return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase()) }
4. 存储操作
- 存储loalStorage
const loalStorageSet = (key, value) => { if (!key) return; if (typeof value !== 'string') { value = JSON.stringify(value); } window.localStorage.setItem(key, value); };
- 获取localStorage
const loalStorageGet = (key) => { if (!key) return; return window.localStorage.getItem(key); };
- 删除localStorage
const loalStorageRemove = (key) => { if (!key) return; window.localStorage.removeItem(key); };
- 存储sessionStorage
const sessionStorageSet = (key, value) => { if (!key) return; if (typeof value !== 'string') { value = JSON.stringify(value); } window.sessionStorage.setItem(key, value) };
- 获取sessionStorage
const sessionStorageGet = (key) => { if (!key) return; return window.sessionStorage.getItem(key) };
- 删除sessionStorage
const sessionStorageRemove = (key) => { if (!key) return; window.sessionStorage.removeItem(key) };
- 设置cookie
Data对象const setCookie = (key, value, expire) => { const d = new Date(); d.setDate(d.getDate() + expire); document.cookie = `${key}=${value};expires=${d.toUTCString()}` };
- 读取cookie
const getCookie = (key) => { // 解码 decodeURI() const cookieStr = decodeURI(document.cookie); const arr = cookieStr.split(';'); let cookieValue = ''; for (let i = 0; i < arr.length; i++) { const temp = arr[i].split('='); if (temp[0] === key) { cookieValue = temp[1]; break } } return cookieValue };
- 删除cookie
const delCookie = (key) => { // 编码 encodeURIComponent() document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}` };
5. URL操作
- 获取URL参数列表
const GetRequest = () => { let url = location.search; const paramsStr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来 const paramsArr = paramsStr.split('&'); // 将字符串以 & 分割后存到数组中 let paramsObj = {}; // 将 params 存到对象中 paramsArr.forEach(param => { if (/=/.test(param)) { // 处理有 value 的参数 let [key, val] = param.split('='); // 分割 key 和 value val = decodeURIComponent(val); // 解码 val = /^\d+$/.test(val) ? parseFloat(val) : val; // 判断是否转为数字 if (paramsObj.hasOwnProperty(key)) { // 如果对象有 key,则添加一个值 paramsObj[key] = [].concat(paramsObj[key], val); } else { // 如果对象没有这个 key,创建 key 并设置值 paramsObj[key] = val; } } else { // 处理没有 value 的参数 paramsObj[param] = true; } }) return paramsObj; };
- 键值对拼接成URL参数
const params2Url = (obj) => { let params = [] for (let key in obj) { params.push(`${key}=${obj[key]}`); } return encodeURIComponent(params.join('&')) }
6. 浏览器操作
- 滚动到页面顶部
const scrollToTop = () => { const height = document.documentElement.scrollTop || document.body.scrollTop; if (height > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, height - height / 8); } }
- 滚动到页面底部
const scrollToBottom = () => { window.scrollTo(0, document.documentElement.clientHeight); }
- 滚动到指定元素区域
const smoothScroll = (element) => { document.querySelector(element).scrollIntoView({ behavior: 'smooth' }); };
- 获取可视窗口高度
const getClientHeight = () => { let clientHeight = 0; if (document.body.clientHeight && document.documentElement.clientHeight) { clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight; } else { clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight; } return clientHeight; }
- 获取可视窗口宽度
export const getPageViewWidth = () => { return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth; }
7. 时间操作
- 当前时间
const nowTime = () => { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth(); const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate()); const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours()); const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes()); const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds()); return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec; }
- 格式化时间
export const dateFormater = (formater, time) => { let date = time ? new Date(time) : new Date(), Y = date.getFullYear() + '', M = date.getMonth() + 1, D = date.getDate(), H = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); return formater.replace(/YYYY|yyyy/g, Y) .replace(/YY|yy/g, Y.substr(2, 2)) .replace(/MM/g,(M<10 ? '0' : '') + M) .replace(/DD/g,(D<10 ? '0' : '') + D) .replace(/HH|hh/g,(H<10 ? '0' : '') + H) .replace(/mm/g,(m<10 ? '0' : '') + m) .replace(/ss/g,(s<10 ? '0' : '') + s) } // dateFormater('YYYY-MM-DD HH:mm:ss') // dateFormater('YYYYMMDDHHmmss')