技术文摘
25 个实用的 JavaScript 代码
2024-12-31 01:30:50 小编
25 个实用的 JavaScript 代码
在当今的网页开发领域,JavaScript 无疑是至关重要的编程语言。以下为您介绍 25 个实用的 JavaScript 代码示例,助您提升开发效率。
- 数组去重
function uniqueArray(arr) {
return Array.from(new Set(arr));
}
- 数组排序
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
- 字符串反转
function reverseString(str) {
return str.split('').reverse().join('');
}
- 生成随机数
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
- 判断闰年
function isLeapYear(year) {
return (year % 4 === 0 && year % 100!== 0) || year % 400 === 0;
}
- 计算阶乘
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
- 检查是否为数字
function isNumber(value) {
return!isNaN(parseFloat(value)) && isFinite(value);
}
- 深拷贝对象
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
- 防抖函数
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, delay);
};
}
- 节流函数
function throttle(func, delay) {
let lastCallTime = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCallTime >= delay) {
func(...args);
lastCallTime = now;
}
};
}
- 获取元素样式
function getStyle(element, property) {
return window.getComputedStyle(element)[property];
}
- 平滑滚动到指定元素
function smoothScrollTo(element) {
element.scrollIntoView({ behavior:'smooth' });
}
- 检测浏览器类型
function detectBrowser() {
const userAgent = navigator.userAgent;
if (userAgent.indexOf('Chrome')!== -1) {
return 'Chrome';
} else if (userAgent.indexOf('Firefox')!== -1) {
return 'Firefox';
} else {
return 'Other';
}
}
- 动态加载脚本
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = callback;
document.head.appendChild(script);
}
- 图片懒加载
function lazyLoadImages() {
const images = document.querySelectorAll('img[data-src]');
images.forEach(image => {
if (image.getBoundingClientRect().top < window.innerHeight && image.getBoundingClientRect().bottom >= 0) {
image.src = image.dataset.src;
image.removeAttribute('data-src');
}
});
}
- 日期格式化
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);
}
- 字符串驼峰转下划线
function camelToSnake(str) {
return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
}
- 下划线转驼峰
function snakeToCamel(str) {
return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
}
- 计算字符串出现次数
function countStringOccurrences(str, target) {
return str.split(target).length - 1;
}
- 简单的轮播图实现
class Carousel {
constructor(images) {
this.images = images;
this.currentIndex = 0;
}
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length;
}
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
}
getCurrentImage() {
return this.images[this.currentIndex];
}
}
- 本地存储操作
function setLocalStorage(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function getLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
function removeLocalStorage(key) {
localStorage.removeItem(key);
}
- 数组元素交换
function swapArrayElements(arr, index1, index2) {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]];
return arr;
}
- 计算两个日期之间的天数差
function daysBetweenDates(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000;
return Math.ceil(Math.abs((date1 - date2) / oneDay));
}
- 字符串截断
function truncateString(str, length) {
return str.length > length? str.slice(0, length) + '...' : str;
}
- 简单的表单验证
function validateForm(form) {
const inputs = form.querySelectorAll('input[required]');
let valid = true;
inputs.forEach(input => {
if (!input.value) {
input.classList.add('invalid');
valid = false;
} else {
input.classList.remove('invalid');
}
});
return valid;
}
这些实用的 JavaScript 代码涵盖了各种常见的功能和场景,希望能为您的开发工作带来便利和启发。不断探索和实践,您将能够更加熟练地运用 JavaScript 创造出更出色的网页应用。
- Kotlin 中有哪些作用域函数
- 探讨接口最大并发处理量
- Istio Egress 出口网关的使用
- Golang 性能优化策略
- 实例解读 Web 应用跨域难题
- 深度剖析 CPU 缓存一致性协议 MESI(建议收藏)
- 微前端架构的初步探索与个人前端技术盘点
- Redis 高可用:集群中的武林秘籍,稳了!
- 快速掌握 CSS @starting-style 规则
- Python 数据的序列化及反序列化:实现高效的数据交换与存储
- SSE 解密:实现如 ChatGPT 的流式响应
- Vue3 中微信扫码授权登录的实现之问
- RabbitMQ 的 Routing 路由工作模式
- Netty 全解析,一文读懂
- RabbitMQ 插件开发指引:实现消息队列定制化