news 2026/4/23 15:37:08

超多JavaScript实用小妙招

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
超多JavaScript实用小妙招

字符串处理

1. 生成随机字符串

const randomString = (length = 8) => { return Math.random().toString(36).slice(2, 2 + length);};// 示例:randomString() → "4f9d2fe3"

2. 首字母大写

const capitalize = (str) => { return str.charAt(0).toUpperCase() + str.slice(1);};// 示例:capitalize("hello") → "Hello"

数组操作

3. 数组去重

const uniqueArray = (arr) => [...new Set(arr)];// 示例:uniqueArray([1,2,2,3]) → [1,2,3]

4. 数组乱序(洗牌算法)

const shuffleArray = (arr) => { return arr.sort(() => Math.random() - 0.5);};// 示例:shuffleArray([1,2,3,4]) → 随机顺序

对象处理

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)) );};// 示例:filterObject({a:1, b:2}, ['a']) → {a:1}

数字处理

7. 千分位格式化

const formatNumber = (num) => { return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");};// 示例:formatNumber(1234567) → "1,234,567"

8. 生成范围随机数

const randomInRange = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min;};// 示例:randomInRange(5, 10) → 5~10之间的整数

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()));};// 示例:formatDate() → "2023-08-15"

函数优化

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();};// 示例:typeOf([]) → "array"

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; } }};

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 14:10:20

3个步骤打造极简随身游戏库:Playnite便携版高效配置指南

3个步骤打造极简随身游戏库:Playnite便携版高效配置指南 【免费下载链接】Playnite Video game library manager with support for wide range of 3rd party libraries and game emulation support, providing one unified interface for your games. 项目地址: h…

作者头像 李华
网站建设 2026/4/23 13:02:31

重构视频编码流程:Hap编码器如何用GPU加速技术颠覆实时视频处理

重构视频编码流程:Hap编码器如何用GPU加速技术颠覆实时视频处理 【免费下载链接】hap-qt-codec A QuickTime codec for Hap video 项目地址: https://gitcode.com/gh_mirrors/ha/hap-qt-codec 在当今视频处理领域,GPU加速视频编码已成为突破性能瓶…

作者头像 李华
网站建设 2026/4/23 14:46:17

7个实战技巧:用Godot Voxel脚本API创建程序化生成洞穴世界

7个实战技巧:用Godot Voxel脚本API创建程序化生成洞穴世界 【免费下载链接】godot_voxel Voxel module for Godot Engine 项目地址: https://gitcode.com/gh_mirrors/go/godot_voxel 在3D游戏开发中,体素世界创建是一项极具挑战性的任务。Godot V…

作者头像 李华
网站建设 2026/4/23 13:01:31

WinDiskWriter:Mac制作Windows启动盘的高效方案

WinDiskWriter:Mac制作Windows启动盘的高效方案 【免费下载链接】windiskwriter 🖥 A macOS app that creates bootable USB drives for Windows. 🛠 Patches Windows 11 to bypass TPM and Secure Boot requirements. 项目地址: https://g…

作者头像 李华
网站建设 2026/4/23 13:02:36

7个技巧掌握Godot Voxel插件核心功能开发

7个技巧掌握Godot Voxel插件核心功能开发 【免费下载链接】godot_voxel Voxel module for Godot Engine 项目地址: https://gitcode.com/gh_mirrors/go/godot_voxel Godot体素开发是创建沉浸式3D世界的关键技术,而Godot Voxel插件为开发者提供了强大的3D地形…

作者头像 李华
网站建设 2026/4/22 23:08:51

5分钟掌握Cowabunga完全指南:iOS系统终极个性化工具箱

5分钟掌握Cowabunga完全指南:iOS系统终极个性化工具箱 【免费下载链接】Cowabunga iOS 14.0-15.7.1 & 16.0-16.1.2 MacDirtyCow ToolBox 项目地址: https://gitcode.com/gh_mirrors/co/Cowabunga Cowabunga是一款基于MacDirtyCow漏洞开发的iOS系统个性化…

作者头像 李华