已实名认证
|
项目里反复用的几个函数,抽出来放 utils 里,省得每次重写。
[h2]1. 防抖[/h2]
- export const debounce = (fn, delay = 300) => {
- let timer;
- return (...args) => {
- clearTimeout(timer);
- timer = setTimeout(() => fn(...args), delay);
- };
- };
复制代码
搜索框输入、窗口 resize 用这个。
[h2]2. 节流[/h2]
- export const throttle = (fn, interval = 300) => {
- let last = 0;
- return (...args) => {
- const now = Date.now();
- if (now - last >= interval) {
- last = now;
- fn(...args);
- }
- };
- };
复制代码
滚动加载、按钮防连点用这个。
防抖和节流的区别:防抖是"停手后才执行",节流是"固定频率执行"。
[h2]3. 深拷贝[/h2]
- export const deepClone = (obj) => {
- if (obj === null || typeof obj !== 'object') return obj;
- if (obj instanceof Date) return new Date(obj);
- if (obj instanceof Array) return obj.map(deepClone);
- return Object.fromEntries(
- Object.entries(obj).map(([k, v]) => [k, deepClone(v)])
- );
- };
复制代码
注意:不支持循环引用和函数。复杂场景还是用 structuredClone。
[h2]4. 格式化文件大小[/h2]
- export const formatSize = (bytes) => {
- if (!bytes) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + units[i];
- };
复制代码
[h2]5. 复制到剪贴板[/h2]
- export const copyText = async (text) => {
- try {
- await navigator.clipboard.writeText(text);
- return true;
- } catch {
- const ta = document.createElement('textarea');
- ta.value = text;
- document.body.appendChild(ta);
- ta.select();
- document.execCommand('copy');
- ta.remove();
- return true;
- }
- };
复制代码
https 环境下剪贴板 API 才有,http 会失败,所以要有降级方案。
[h2]6. 获取 URL 参数[/h2]
- export const getQuery = (key) => new URLSearchParams(location.search).get(key);
复制代码
 |
|