技术文摘
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 开发中的常见需求,希望能对您的编程工作有所帮助,让您的代码更加简洁高效。
- Go 语言中的心跳机制实现
- 详解 Golang 中通过接口实现 Apply 方法的配置模式
- Go 语言可选参数实现方法汇总
- 在 Windows 上运用 Go 语言设置全局快捷键的操作
- 命令行实现 JSON 数据到 CSV 的一键导出
- jq 命令在 JSON 中的过滤、遍历、结构转换操作实例
- GORM 默认 SQLite 驱动更换问题的解决分析
- 反弹 shell 进阶至全交互式 shell
- go 交叉编译 sqlite 报错问题的解决与分析
- Linux 中基于一个单词快速锁定日志的操作命令
- 六个提升 golang 源码阅读效率的高级窍门
- Linux 中非登录系统用户执行命令的实现方法
- Shell -z 与 -n 的使用差异
- 利用 PowerShell 编写持续单击 J 键的脚本
- Shell 中的条件、变量、表达式 0 和 1 及数值与字符串判断