技术文摘
22 个高频实用的 JavaScript 片段(2020 年)
2024-12-31 08:53:47 小编
22 个高频实用的 JavaScript 片段(2020 年)
在 JavaScript 的世界里,掌握一些实用的代码片段可以极大地提高开发效率。以下为您精心整理了 22 个在 2020 年高频使用的 JavaScript 片段。
- 数组去重
function uniqueArray(arr) {
return Array.from(new Set(arr));
}
- 数组扁平化
function flattenArray(arr) {
return arr.reduce((acc, val) => acc.concat(Array.isArray(val)? flattenArray(val) : val), []);
}
- 对象属性拷贝
function copyObject(obj) {
return Object.assign({}, obj);
}
- 字符串反转
function reverseString(str) {
return str.split('').reverse().join('');
}
- 生成随机字符串
function generateRandomString(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
- 计算数组平均值
function averageOfArray(arr) {
return arr.reduce((a, b) => a + b) / arr.length;
}
- 检查对象是否为空
function isEmptyObject(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
- 防抖函数
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
- 节流函数
function throttle(func, delay) {
let lastCallTime = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCallTime >= delay) {
func.apply(this, args);
lastCallTime = now;
}
};
}
- 格式化货币
function formatCurrency(amount, currencyCode) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: currencyCode }).format(amount);
}
- 深拷贝对象
function deepCopy(obj) {
if (typeof obj!== 'object' || obj === null) {
return obj;
}
let newObj;
if (Array.isArray(obj)) {
newObj = [];
} else {
newObj = {};
}
for (let key in obj) {
newObj[key] = deepCopy(obj[key]);
}
return newObj;
}
- 判断数据类型
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
- 滚动到页面顶部
function scrollToTop() {
window.scrollTo(0, 0);
}
- 获取 URL 参数
function getUrlParams() {
const params = new URLSearchParams(window.location.search);
const result = {};
for (const [key, value] of params) {
result[key] = value;
}
return result;
}
- 数字补零
function padZero(num, length) {
return String(num).padStart(length, '0');
}
- 数组排序
function sortArray(arr, asc = true) {
return asc? arr.sort((a, b) => a - b) : arr.sort((a, b) => b - a);
}
- 数组随机排序
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
- 计算字符串长度(包括中文字符)
function getStringLength(str) {
return str.split('').reduce((acc, cur) => acc + (/[\u4e00-\u9fff]/.test(cur)? 2 : 1), 0);
}
- 日期格式化
function formatDate(date, format = 'yyyy-MM-dd') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return format.replace('yyyy', year).replace('MM', month).replace('dd', day);
}
- 异步加载脚本
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = callback;
document.head.appendChild(script);
}
- 切换元素显示与隐藏
function toggleElementVisibility(elem) {
if (window.getComputedStyle(elem).display === 'none') {
elem.style.display = 'block';
} else {
elem.style.display = 'none';
}
}
- 检测元素是否在视口内
function isElementInViewport(elem) {
const rect = elem.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
这些 JavaScript 片段在日常开发中经常会用到,熟练掌握它们可以让您的开发工作更加高效和便捷。
- Wn11 定位功能呈灰色的原因及解决办法
- Vmware 虚拟机安装 Win11 不兼容的解决方法及 Win11 正式版 64 位虚拟机专用系统下载
- Win11 天气预报定位错误的原因及解决办法
- 2023 年超实用的 Win11 22H2 企业版永久激活下载
- Win11 提示音关闭方法:系统开机提示音教学
- Win11 无法下载第三方软件的解决之道
- Win11 系统中如何查看电脑主板信息 教程
- Win11 电脑显卡温度的查看方法分享
- 解决 Win11 时钟显示不全的办法
- Win11 体验计划的加入方式分享
- Win11 系统 edge 浏览器标签页为何自动弹出
- 外星人 M15 R7 笔记本 Win11 一键重装系统教程
- 如何使 Windows 11 系统托盘显示秒数
- 如何解决 Win11 双击文件夹弹出属性的问题
- Win11 笔记本电脑无法充电的原因及解决办法分享