吾爱编程

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 25|回复: 0

前端常用的 6 个工具函数,建议收进 utils

[复制链接]
已实名认证

8

主题

0

回帖

14

积分
积分成就

成长值:5 点

吾爱币:8 枚

荣誉值:0 点

活跃数据

在线:6 小时

注册:2026-11-20

最后:2026-11-26

勋章
发表于 昨天 21:16 | 显示全部楼层 |阅读模式
项目里反复用的几个函数,抽出来放 utils 里,省得每次重写。

[h2]1. 防抖[/h2]

  1. export const debounce = (fn, delay = 300) => {
  2.   let timer;
  3.   return (...args) => {
  4.     clearTimeout(timer);
  5.     timer = setTimeout(() => fn(...args), delay);
  6.   };
  7. };
复制代码

搜索框输入、窗口 resize 用这个。

[h2]2. 节流[/h2]

  1. export const throttle = (fn, interval = 300) => {
  2.   let last = 0;
  3.   return (...args) => {
  4.     const now = Date.now();
  5.     if (now - last >= interval) {
  6.       last = now;
  7.       fn(...args);
  8.     }
  9.   };
  10. };
复制代码

滚动加载、按钮防连点用这个。

防抖和节流的区别:防抖是"停手后才执行",节流是"固定频率执行"。

[h2]3. 深拷贝[/h2]

  1. export const deepClone = (obj) => {
  2.   if (obj === null || typeof obj !== 'object') return obj;
  3.   if (obj instanceof Date) return new Date(obj);
  4.   if (obj instanceof Array) return obj.map(deepClone);
  5.   return Object.fromEntries(
  6.     Object.entries(obj).map(([k, v]) => [k, deepClone(v)])
  7.   );
  8. };
复制代码

注意:不支持循环引用和函数。复杂场景还是用 structuredClone。

[h2]4. 格式化文件大小[/h2]

  1. export const formatSize = (bytes) => {
  2.   if (!bytes) return '0 B';
  3.   const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  4.   const i = Math.floor(Math.log(bytes) / Math.log(1024));
  5.   return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + units[i];
  6. };
复制代码


[h2]5. 复制到剪贴板[/h2]

  1. export const copyText = async (text) => {
  2.   try {
  3.     await navigator.clipboard.writeText(text);
  4.     return true;
  5.   } catch {
  6.     const ta = document.createElement('textarea');
  7.     ta.value = text;
  8.     document.body.appendChild(ta);
  9.     ta.select();
  10.     document.execCommand('copy');
  11.     ta.remove();
  12.     return true;
  13.   }
  14. };
复制代码

https 环境下剪贴板 API 才有,http 会失败,所以要有降级方案。

[h2]6. 获取 URL 参数[/h2]

  1. export const getQuery = (key) => new URLSearchParams(location.search).get(key);
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

论坛首页技术专区源码区教程分享区问答求助[火山平台专区]

拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表本站立场!

论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到您的权益,请联系我们!

防范网络诈骗,远离网络犯罪 违法和不良信息举报:admin@5abc.cn

网站简介:吾爱编程·编程社区 是一个面向编程技术爱好者的交流社区,欢迎大家在这里分享经验、交流心得。

吾爱编程·编程社区 黔ICP备2024033742号-2 公安备案贵公网安备52022202000354号

快速回复 返回顶部 返回列表