技术文摘
21 个简便实用的 JavaScript 代码片段
2024-12-30 18:45:44 小编
21 个简便实用的 JavaScript 代码片段
在 JavaScript 的世界里,掌握一些实用的代码片段可以大大提高开发效率。以下为您介绍 21 个简便且实用的 JavaScript 代码片段。
- 数组去重
const uniqueArray = arr => [...new Set(arr)];
- 数组扁平化
const flattenArray = arr => arr.flat(Infinity);
- 计算数组平均值
const average = arr => arr.reduce((a, b) => a + b) / arr.length;
- 检查对象是否为空
const isEmptyObject = obj => Object.keys(obj).length === 0;
- 深拷贝对象
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
- 字符串首字母大写
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
- 生成随机字符串
const generateRandomString = length => Math.random().toString(36).substr(2, length);
- 检查变量是否为数字
const isNumber = value =>!isNaN(parseFloat(value)) && isFinite(value);
- 防抖函数
const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
};
- 节流函数
const throttle = (func, limit) => {
let lastCall = 0;
return (...args) => {
const now = new Date().getTime();
if (now - lastCall >= limit) {
func(...args);
lastCall = now;
}
};
};
- 格式化货币
const formatCurrency = (amount, currency = 'USD') => new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount);
- 数组排序
const sortArray = arr => arr.sort((a, b) => a - b);
- 数组筛选
const filterArray = (arr, condition) => arr.filter(condition);
- 字符串反转
const reverseString = str => str.split('').reverse().join('');
- 计算字符串出现次数
const countOccurrences = (str, subStr) => str.split(subStr).length - 1;
- 获取 URL 参数
const getUrlParams = () => {
const params = new URLSearchParams(window.location.search);
const result = {};
for (const [key, value] of params) {
result[key] = value;
}
return result;
};
- 滚动到页面顶部
const scrollToTop = () => window.scrollTo(0, 0);
- 检查元素是否在视口内
const isElementInViewport = el => {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
- 切换类名
const toggleClass = (el, className) => el.classList.toggle(className);
- 延迟执行函数
const delayFunction = (func, delay) => setTimeout(func, delay);
- 检测浏览器类型
const detectBrowser = () => {
const userAgent = navigator.userAgent;
if (userAgent.includes('Chrome')) {
return 'Chrome';
} else if (userAgent.includes('Firefox')) {
return 'Firefox';
} else if (userAgent.includes('Safari')) {
return 'Safari';
} else if (userAgent.includes('Edge')) {
return 'Edge';
} else {
return 'Unknown';
}
};
这些代码片段涵盖了 JavaScript 开发中的常见需求,希望能对您的编程工作有所帮助,让您的代码更加简洁高效。
- GoLand中自动生成其他包的接口方法实现的方法
- Go程序跨机运行遇段错误,CGO依赖兼容性问题该如何解决
- Python Pipe进程间通信收不到消息,参数传递错误该如何解决
- Gorm Postgres中自定义类型主键的自增实现方法
- Windows系统下用select做IO多路复用为何不能监听文件对象
- Python垃圾回收机制中重复实例化对象触发__del__方法致异常原因
- PyMySQL中如何安全格式化SQL语句避免语法错误
- pip install -e. 有何作用
- 如何为企业挑选合适的AI模型?
- Go程序跨平台运行时syscall依赖问题的解决方法
- Python读取HTML文件时通过Socket发送HTTP请求后内容不完整原因探究
- Goland中自动生成接口方法的方法
- GoLand中自动生成其他包接口方法实现的方法
- Pillow直接显示Matplotlib生成图片的方法
- 进程结束时信号量自动释放的原理