技术文摘
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 函数 实用技巧 函数编程 代码片段
- C++中CreateThread参数的具体应用技巧解析
- C++托管程序下的安全管理实现
- C++文件拷贝应用技巧解析
- C++ replace()函数基本应用方法汇总
- C++中strtok的应用方式简析
- Linux Kernel驱逐Android,究竟是怎么回事
- 专家论ASP.NET与PHP的未来发展
- 微软正式发布Windows Phone 7系列
- 2月编程语言排行榜:Objective-C的挽歌
- 诺基亚与英特尔携手推出Linux系统MeeGo
- JVM内存模型与垃圾收集策略剖析
- Visual Studio DSL创建状态机元数据模型详解
- Spring 3.0.1发布 带来新JSP标记类库
- Python语言的正确使用方法
- Python语言说明介绍图解