字符串处理
1. 生成随机字符串
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);
};
数组操作
3. 数组去重
const uniqueArray = (arr) => [...new Set(arr)];
4. 数组乱序(洗牌算法)
const shuffleArray = (arr) => {
return arr.sort(() => Math.random() - 0.5);
};
对象处理
5. 深拷贝(简易版)
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
6. 对象属性过滤
const filterObject = (obj, keys) => {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => keys.includes(key))
);
};
数字处理
7. 千分位格式化
const formatNumber = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
8. 生成范围随机数
const randomInRange = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
DOM 相关
9. 复制内容到剪贴板
const copyToClipboard = (text) => {
navigator.clipboard.writeText(text);
};
10. 检测元素是否可见
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()));
};
函数优化
12. 防抖函数(Debounce)
const debounce = (fn, delay = 300) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
};
13. 节流函数(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. 类型判断增强版
const typeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
15. 本地存储封装
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 编辑过