返回
前端必备的Javascript代码片段
前端
2024-01-15 04:12:51
在日常开发中,为了快速解决各种问题,常常需要借助一些代码片段来实现。JavaScript 作为一种流行的编程语言,拥有丰富的代码片段库。本文列出了 16 个实用的 JavaScript 代码片段,涵盖了从随机排列数组到检查日期是否有效等各个方面。
1. 随机排列数组
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
2. 检查日期是否有效
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
3. 复制到剪贴板
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
console.log("Copied to clipboard!");
}, () => {
console.log("Failed to copy to clipboard!");
});
}
4. 计算两个日期之间的天数
function daysBetween(date1, date2) {
const oneDay = 1000 * 60 * 60 * 24;
const difference = Math.abs(date1 - date2);
return Math.ceil(difference / oneDay);
}
5. 格式化日期
function formatDate(date, format) {
const options = {
year: "numeric",
month: "long",
day: "numeric",
};
return new Intl.DateTimeFormat("en-US", options).format(date);
}
6. 获取元素的相对位置
function getRelativePosition(element, relativeTo) {
const rect = element.getBoundingClientRect();
const relativeRect = relativeTo.getBoundingClientRect();
return {
top: rect.top - relativeRect.top,
left: rect.left - relativeRect.left,
};
}
7. 检测设备类型
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
8. 创建和下载文件
function createAndDownloadFile(data, filename, mimeType) {
const blob = new Blob([data], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
9. 在两个元素之间添加一个元素
function insertElementBetween(newElement, targetElement, position) {
if (position === "before") {
targetElement.parentNode.insertBefore(newElement, targetElement);
} else if (position === "after") {
targetElement.parentNode.insertBefore(newElement, targetElement.nextSibling);
} else {
console.error("Invalid position: " + position);
}
}
10. 计算元素的大小
function getBoundingClientRect(element) {
return element.getBoundingClientRect();
}
11. 检测是否为触摸屏设备
function isTouchEventSupported() {
return "ontouchstart" in window || navigator.maxTouchPoints > 0;
}
12. 生成随机数
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
13. 在控制台中打印对象
function printObject(object) {
console.log(JSON.stringify(object, null, 2));
}
14. 从数组中删除元素
function removeElementFromArray(array, element) {
const index = array.indexOf(element);
if (index !== -1) {
array.splice(index, 1);
}
}
以上的 16 个代码片段涵盖了 JavaScript 开发中常见的任务,能够帮助您快速解决各种问题。希望这些代码片段对您有所帮助。