字符串處理
1. 生成隨機(jī)字符串
const randomString = (length = 8) => { return Math.random().toString(36).slice(2, 2 + length);};
2. 首字母大寫
const capitalize = (str) => { return str.charAt(0).toUpperCase() + str.slice(1);};
數(shù)組操作
3. 數(shù)組去重
const uniqueArray = (arr) => [...new Set(arr)];
4. 數(shù)組亂序(洗牌算法)
const shuffleArray = (arr) => { return arr.sort(() => Math.random() - 0.5);};
對(duì)象處理
5. 深拷貝(簡(jiǎn)易版)
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
6. 對(duì)象屬性過濾
const filterObject = (obj, keys) => { return Object.fromEntries( Object.entries(obj).filter(([key]) => keys.includes(key)) );};
數(shù)字處理
7. 千分位格式化
const formatNumber = (num) => { return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");};
8. 生成范圍隨機(jī)數(shù)
const randomInRange = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min;};
DOM 相關(guān)
9. 復(fù)制內(nèi)容到剪貼板
const copyToClipboard = (text) => { navigator.clipboard.writeText(text);};
10. 檢測(cè)元素是否可見
const isElementVisible = (el) => { return el.offsetParent !== null;};
日期處理
11. 格式化日期
const formatDate = (date = new Date(), format = 'YYYY-MM-DD') => { const pad = n => n.toString().padStart(2, '0'); return format .replace('YYYY', date.getFullYear()) .replace('MM', pad(date.getMonth() + 1)) .replace('DD', pad(date.getDate()));};
函數(shù)優(yōu)化
12. 防抖函數(shù)(Debounce)
const debounce = (fn, delay = 300) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); };};
13. 節(jié)流函數(shù)(Throttle)
const throttle = (fn, interval = 300) => { let lastTime = 0; return (...args) => { const now = Date.now(); if (now - lastTime >= interval) { fn.apply(this, args); lastTime = now; } };};
14. 類型判斷增強(qiáng)版
const typeOf = (obj) => { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();};
15. 本地存儲(chǔ)封裝
const storage = { set: (key, value) => localStorage.setItem(key, JSON.stringify(value)), get: (key) => { try { return JSON.parse(localStorage.getItem(key)); } catch (e) { return null; } }};
該文章在 2025/5/7 12:20:37 編輯過