JavaScript常用技巧专题二

2023-12-13 05:04:34


一、前言

本专题主要是分享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)

十三、、最后

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

文章来源:https://blog.csdn.net/u012804440/article/details/134916725
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。