技术文摘
11 个实用的 JavaScript 函数代码片段
2024-12-30 22:44:50 小编
11 个实用的 JavaScript 函数代码片段
在 JavaScript 开发中,掌握一些实用的函数代码片段可以大大提高开发效率。以下为您介绍 11 个常用且实用的 JavaScript 函数代码片段。
- 数组去重函数
function uniqueArray(arr) {
return Array.from(new Set(arr));
}
- 数组求和函数
function sumArray(arr) {
return arr.reduce((a, b) => a + b, 0);
}
- 字符串反转函数
function reverseString(str) {
return str.split('').reverse().join('');
}
- 生成随机数函数
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
- 检查对象是否为空函数
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
- 深拷贝函数
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
- 防抖函数
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
- 节流函数
function throttle(func, delay) {
let lastExecuted = 0;
return function (...args) {
const now = Date.now();
if (now - lastExecuted >= delay) {
func.apply(this, args);
lastExecuted = now;
}
};
}
- 获取元素样式函数
function getStyle(element, property) {
return window.getComputedStyle(element)[property];
}
- 平滑滚动到页面顶部函数
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
- 格式化日期函数
function formatDate(date, format) {
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
return new Intl.DateTimeFormat('en-US', options).format(date);
}
这些函数代码片段在实际开发中经常会用到,希望它们能为您的 JavaScript 编程带来便利和效率提升。不断积累和运用这些实用的函数,将有助于您编写出更加优质和高效的代码。
TAGS: JavaScript 函数 实用技巧 函数编程 代码片段
- MySQL EXTRACT() 函数可使用的复合单元有哪些
- 如何指定MySQL输出中返回的记录数
- 怎样制作 MySQL 克隆表
- MySQL NULL 安全等于运算符是什么,与比较运算符有何差异?
- 如何找出MySQL中特定表使用的存储引擎
- 如何通过命令行知晓已安装的 MongoDB 版本
- MySQL 允许优化和修复的最低用户权限是多少
- CONCAT_WS() 函数与 MySQL WHERE 子句的联用方法
- MySQL COALESCE() 函数如何在列的 NULL 位置插入值
- 如何在 MySQL 中让现有字段变为唯一
- MySQL 中如何显示表命令的约束
- MySQL 系统变量与局部变量解析
- MySQL 中 CHAR 与 NCHAR 的差异
- 列出 MySQL 表并按大小排序及显示大小
- 怎样在单个查询里获取多个 MySQL 表的输出