技术文摘
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 开发中的常见需求,希望能对您的编程工作有所帮助,让您的代码更加简洁高效。
- JavaScript两种解析引擎性能对比探讨
- Python线程编程彰显语言新特性方法
- Python字典于linux系统下的相关讲解
- 探秘Java虚拟机:解析JVM里的Stack与Heap
- Python线程编程相对于Ruby应用的优势
- Python type类三大具体分类介绍
- Python 3.0 beta 1超简洁语法的运用
- Python列表元素变量的实现方法
- 如何更好地学习Python内置对象
- Python编程语言创始人眼中的前景
- Python中Hello World程序的运行操作方法
- Python分割器助力文章精细处理
- Python模块使用时的两种导入方法
- Python运行时退出Python提示符的操作方法
- Python编程语言的学习选择方法