JavaScript常用技巧专题二

本文介绍了JavaScript中的一系列实用技巧,包括生成随机字符串、HTML转义、文本格式化(如单词首字母大写和小驼峰命名)、数组操作(去重、移除假值),以及日期计算、RGB颜色转换和检测黑暗模式等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、前言

本专题主要是分享JavaScript实用小技巧,希望能提高大家的工作效率。

二、生成随机字符串

当我们需要一个唯一id时,通过Math.random创建一个随机字符串

const randomString = () => Math.random().toString(36).slice(2)
console.log(randomString()) // ugvy2k3eiqq
console.log(randomString()) // f4s72hycpfr
console.log(randomString()) //1xg2nsbsfnb

三、转义HTML特殊字符

解决XSS方法之一就是转义HTML

const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]))
console.log(escape('<div class="medium">Hi Medium.</div>'))
// &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt;

四、单词首字母大写

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
console.log(uppercaseWords('hello world')) // 'Hello World'

五、将字符串转换为小驼峰

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
console.log(toCamelCase('background-color')); // backgroundColor
console.log(toCamelCase('-webkit-scrollbar-thumb')); // WebkitScrollbarThumb
console.log(toCamelCase('_hello_world')); // HelloWorld
console.log(toCamelCase('hello_world')); // helloWorld

六、删除数组中的重复值

得益于ES6,使用Set数据类型来对数组去重太方便了。

const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) 
// [1, 2, 3, 4, 5, 6]

七、移除数组中的假值

const removeFalsy = (arr) => arr.filter(Boolean)
console.log(removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]))
// ['a string', true, 5, 'another string']

八、获取两个数字之间的随机数

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
console.log(random(1, 50)) // 48
console.log(random(1, 50)) // 6

九、将数字截断到固定的小数点

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
console.log(round(1.005, 2)) // 1.01
console.log(round(1.555, 2)) // 1.56

十、日期

10.1、计算两个日期之间天数

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
console.log(diffDays(new Date("2021-11-3"), new Date("2022-2-1")))  // 90

10.2、从日期中获取是一年中的哪一天

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
console.log(dayOfYear(new Date())) // 344

十一、将RGB颜色转换为十六进制颜色值

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
console.log(rgbToHex(255, 255, 255))  // '#ffffff'

十二、检测黑暗模式

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

十三、、最后

本人每篇文章都是一字一句码出来,希望对大家有所帮助,多提提意见。顺手来个三连击,点赞👍收藏💖关注✨,一起加油☕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小马甲丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值