技术文摘
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 开发中的常见需求,希望能对您的编程工作有所帮助,让您的代码更加简洁高效。
- Next.js中Route Handler的作用究竟是什么
- 弹性盒子布局中项目对齐方式该如何调整
- 若依框架切换标签页时页面重载问题的解决方法
- 仅在CSS中为无属性HTML标签设置样式的方法
- 使用ESLint时是否仍需进行Tree Shaking
- Vue 应用程序如何挑选轻量化且易集成的即时通讯方案
- 使用高德地图时全局引入 mock.js 致地图无法加载的解决办法
- CSS创建方形弧形透明背景的方法
- 怎样使用无官方调用方法的npm包
- 父级与子级组件 ID 值不同时,怎样匹配数据表格的选中状态
- 微信扫码登录后怎样关闭弹窗并刷新窗口
- 怎样获取 JavaScript 动态操作后的网页 HTML 代码
- 网页打印样式缺失?教你让打印内容与屏幕显示一致的方法
- CSS布局里 height、max-height 和 min-height 的优先级及作用顺序是怎样的
- 小公司业务组件库开发:ElementUI二次开发还是二次封装?打包工具Webpack还是Rollup?