编程 55个常用的JavaScript代码段

2024-11-18 22:38:45 +0800 CST views 537

#55个常用的JavaScript代码段

本文从简单到复杂列出了一些前端常用的代码段。熟练运用这些代码,可以让你的代码更高效,同时在某些场景下还能让代码更难理解。作为公司的前端核心人员,这些技巧会让你成为不可或缺的顶梁柱。

简单部分

1. 数组平铺

将多维数组快速转换为一维数组:

const flatArray = [].concat(...arr);

2. 手动延时xx毫秒

在异步编程中使用的延时函数:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

3. 数组随机排序

生成一个随机排序的数组(如洗牌功能):

const randomArr = (arr) => arr.sort(() => Math.random() - 0.5);

4. 数组去重

利用Set对象自动去掉重复元素:

const getSingleArr = (arr) => [...new Set(arr)];

5. 一键给网页上边框

用于调试DOM布局:

[].forEach.call($$('*'), function (a) {
    a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
});

6. 一键查看密码

通过修改input框的type属性查看密码:

javascript: alert('password:' + document.querySelectorAll('input[type=password]')[0].value);

7. 一键隐藏鼠标

让页面无法显示鼠标指针,防止他人调试页面:

document.body.style.cursor = 'none';

8. 检查日期是否是周末

判断传入日期是否是周末:

const isWeekend = (date) => date.getDay() === 6 || date.getDay() === 0;

9. 检查日期是否在某年内

判断日期是否属于指定年份:

const isInAYear = (date, year) => date.getUTCFullYear() === new Date(`${year}`).getUTCFullYear();

10. 检查日期是否有效

检测日期是否有效:

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid('December 14, 2024 11:19:00'); // true

11. 计算两个日期间的时间差

以天为单位计算日期差异:

const dayDif = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000);
dayDif(new Date('2023-11-3'), new Date('2024-2-1')); // 90

12. 计算从年初至今的天数

计算当前日期在本年度的第几天:

const dayOfYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
dayOfYear(new Date()); // 258

13. 返回时间的时分秒格式

获取日期的时间部分,格式化为hh:mm:ss

const getTimeFormat = (date) => date.toTimeString().slice(0, 8);
getTimeFormat(new Date()); // 11:26:00

14. 字符串首字母大写

将字符串的首字母大写:

const strFirstBug = (str) => str.charAt(0).toUpperCase() + str.slice(1);
strFirstBug('hello world'); // Hello world

15. 字符串反转

将字符串倒序排列:

const reStr = (str) => str.split('').reverse().join('');
reStr('hello world'); // 'dlrow olleh'

16. 生成随机字符串

生成一个随机字符串:

const randomString = () => Math.random().toString(36).slice(2);

17. 截取字符串并添加省略号

截取字符串,并在超过指定长度时添加省略号:

const substr = (str, len) => (str.length < len ? str : `${str.slice(0, len - 3)}...`);
substr('Hi, I should be truncated because I am too loooong!', 36); // 'Hi, I should be truncated because...'

18. 删除字符串中的HTML内容

移除字符串中的HTML标签内容:

const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';

19. 判断数组是否为空

判断数组是否非空:

const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true

20. 数组合并

将两个数组合并为一个数组:

const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];

21. 判断数字是奇数还是偶数

判断一个数字是否为偶数:

const isEven = (num) => num % 2 === 0;

22. 计算平均值

计算一组数字的平均值:

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

23. 获取随机数

获取0到指定数之间的随机整数:

const random = (max) => Math.floor(Math.random() * max);
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

24. 四舍五入到指定小数位

对数字进行四舍五入,返回数字或字符串:

const round = (n, d) => Number(Math.round(n + 'e' + d) + 'e-' + d);
const round2 = (n, d) => n.toFixed(d);

25. 获取随机颜色

生成一个随机十六进制颜色值:

const randomHex = () =>
    `#${Math.floor(Math.random() * 0xffffff)
        .toString(16)
        .padEnd(6, '0')}`;

26. 复制内容到剪贴板

使用浏览器API复制内容到剪贴板:

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

27. 清除所有Cookies

清除所有已设置的Cookies:

const clearCookies = document.cookie.split(';').forEach((cookie) => (document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)));

28. 获取选中的文本

获取用户框选的文本内容:

const getSelectedText = () => window.getSelection().toString();

29. 检测黑暗模式

检测当前页面是否处于黑暗模式:

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

30. 返回页面顶部

让页面滚动回到顶部:

const goToTop = () => window.scrollTo(0, 0);

31. 检测标签页是否处于激活模式

检测当前页面是否为激活状态:

const isTabInView = () => !document.hidden;

32. 判断设备是否为苹果设备

判断当前浏览设备是否为苹果设备:

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);

33. 检测页面是否滚动到底部

判断页面是否滚动到底部:

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

34. 打开打印模式

调用浏览器的打印对话框:

const showPrintDialog = () => window.print();

35. 检测对象是否为空

检测一个对象是否为空:

const isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

有点难度

36. 生成18位UUID

生成唯一的UUID:

const generateUUID = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateUUID));

37.

RGB转十六进制颜色
将RGB颜色转换为十六进制格式:

const rgbToHex = (r, g, b) => '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

38. 十六进制转RGB颜色

将十六进制颜色转换为RGB格式:

const hexToRGB = (hex) =>
    hex
        .replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)
        .substring(1)
        .match(/.{2}/g)
        .map((x) => parseInt(x, 16));

39. 浅拷贝对象

实现浅拷贝对象:

const shallowClone = (obj) => Object.assign({}, obj);

40. 深拷贝对象

实现深拷贝对象:

const deepClone = (obj) => {
    if (obj === null) return null;
    let clone = Object.assign({}, obj);
    Object.keys(clone).forEach((key) => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]));
    if (Array.isArray(obj)) {
        clone.length = obj.length;
        return Array.from(clone);
    }
    return clone;
};

41. 检测设备是否为移动端

通过检查navigator.userAgent判断设备是否为移动端设备:

const isMobileDevice = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

42. 检测用户是否在线

使用navigator.onLine检测用户是否连接网络:

const isOnline = () => navigator.onLine;

43. 浏览器的全屏模式

触发和退出浏览器的全屏模式:

const toggleFullScreen = () => {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
    } else if (document.exitFullscreen) {
        document.exitFullscreen();
    }
};

44. 生成随机布尔值

生成一个随机的布尔值(truefalse):

const randomBoolean = () => Math.random() >= 0.5;

45. 随机获取数组中的元素

从数组中随机获取一个元素:

const getRandomItem = (arr) => arr[Math.floor(Math.random() * arr.length)];

46. 获取URL参数

从URL中获取指定的查询参数:

const getURLParam = (key) => new URLSearchParams(window.location.search).get(key);

47. 检查字符串是否为URL

通过正则表达式验证字符串是否是URL:

const isValidURL = (str) => {
    const pattern = new RegExp('^(https?:\\/\\/)?' + // 协议
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|' + // 域名
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // IP地址
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // 端口和路径
        '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串
        '(\\#[-a-z\\d_]*)?$', 'i'); // 哈希
    return !!pattern.test(str);
};

48. 检测浏览器类型

根据navigator.userAgent检测当前浏览器的类型:

const getBrowserType = () => {
    const userAgent = navigator.userAgent;
    if (userAgent.indexOf('Firefox') > -1) return 'Firefox';
    if (userAgent.indexOf('Chrome') > -1) return 'Chrome';
    if (userAgent.indexOf('Safari') > -1) return 'Safari';
    if (userAgent.indexOf('MSIE') > -1 || !!document.documentMode) return 'IE'; // IE 11及以下
    return 'Unknown';
};

检测浏览器是否启用了cookie

const isCookieEnabled = () => navigator.cookieEnabled;

50. 监听窗口大小变化

监听窗口的resize事件,自动调整页面布局:

window.addEventListener('resize', () => {
    console.log(`Width: ${window.innerWidth}, Height: ${window.innerHeight}`);
});

51. 深冻结对象

深度冻结对象,使其不可修改:

const deepFreeze = (obj) => {
    Object.keys(obj).forEach((key) => {
        if (typeof obj[key] === 'object' && obj[key] !== null) deepFreeze(obj[key]);
    });
    return Object.freeze(obj);
};

52. 查找数组中的最大值

使用Math.max获取数组中的最大值:

const max = (arr) => Math.max(...arr);

53. 查找数组中的最小值

使用Math.min获取数组中的最小值:

const min = (arr) => Math.min(...arr);

54. 将数字转为货币格式

将数字格式化为货币格式,添加逗号分隔符:

const formatCurrency = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

55. 查找指定元素在数组中的所有索引

返回数组中所有匹配指定值的索引位置:

const findAllIndices = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

以上代码段覆盖了55个前端常见的实用代码技巧,涵盖了数组操作、字符串处理、日期处理、设备检测、UI交互等多方面。通过掌握这些代码,你能够在前端开发中更快、更优雅地解决问题。

复制全文 生成海报 编程 前端 JavaScript 开发技巧 技术

推荐文章

html折叠登陆表单
2024-11-18 19:51:14 +0800 CST
全新 Nginx 在线管理平台
2024-11-19 04:18:33 +0800 CST
OpenCV 检测与跟踪移动物体
2024-11-18 15:27:01 +0800 CST
Rust开发笔记 | Rust的交互式Shell
2024-11-18 19:55:44 +0800 CST
使用Python提取图片中的GPS信息
2024-11-18 13:46:22 +0800 CST
利用图片实现网站的加载速度
2024-11-18 12:29:31 +0800 CST
Vue3中的v-for指令有什么新特性?
2024-11-18 12:34:09 +0800 CST
Python 基于 SSE 实现流式模式
2025-02-16 17:21:01 +0800 CST
为什么大厂也无法避免写出Bug?
2024-11-19 10:03:23 +0800 CST
实用MySQL函数
2024-11-19 03:00:12 +0800 CST
Nginx 防止IP伪造,绕过IP限制
2025-01-15 09:44:42 +0800 CST
Vue3中哪些API被废弃了?
2024-11-17 04:17:22 +0800 CST
快手小程序商城系统
2024-11-25 13:39:46 +0800 CST
程序员茄子在线接单