技术文摘
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 开发中的常见需求,希望能对您的编程工作有所帮助,让您的代码更加简洁高效。
- 朋友送我编程机器人,宣称程序员将下岗
- 5 分钟构建 Node.js 微服务原型
- 从 1 到 10 万用户的应用程序,不同扩展方案如何设计?
- 微软 GitHub 收购 npm 或引领开源新局面 影响 1200 万开发者
- 7 个简易却棘手的 JavaScript 面试题
- 中移雄研咨询:我国数字政府发展现况及案例研究
- Python 工程师必备面试题
- 多文件 C 语言程序的组织构建(一)
- Python 中编译与反编译的安全之道
- 女友执意追问我何为设计模式!
- 百万级商品数据实时同步的秒级搜索系统设计之道
- Python 实现 SQL 自动化的方法
- 页面输入网址回车后至显示内容期间的经历
- 解析 Spring 中所运用的设计模式
- 互联网员工在降薪、待岗与裁员中挣扎求生