提升 JavaScript 知识技能和工作效率的单行代码片段
1. 将内容复制到剪贴板
const copyToClipboard = (content) => navigator.clipboard.writeText(content)
copyToClipboard("Hello fatfish")
2. 获取鼠标选择-获取用户选择的内容
const getSelectedText = () => window.getSelection().toString()
getSelectedText()
3. 打乱数组
const shuffleArray = array => array.sort(() => Math.random() - 0.5)
shuffleArray([ 1, 2,3,4, -1, 0 ])
4. 将 rgba 转换为十六进制
const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')
rgbaToHex(0, 0 ,0)
5. 将十六进制转换为 rgba
const hexToRgba = hex => { const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16)) return `rgba(${r}, ${g}, ${b}, 1)`;}
hexToRgba('#000000')
hexToRgba('#ff007f')
6. 获取多个数字的平均值-使用 reduce 函数
const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length
average(0, 1, 2, -1, 9, 10)
7. 检查数字是偶数还是奇数
const isEven = num => num % 2 === 0
isEven(2)
isEven(1)
8. 删除数组中的重复元素
const uniqueArray = (arr) => [...new Set(arr)]
uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ])
9. 检查对象是否为空对象
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
isEmpty({})
isEmpty({ name: 'fatfish' })
10. 反转字符串
const reverseStr = str => str.split('').reverse().join('')
reverseStr('fatfish')
11. 计算两个日期之间的间隔
const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)
dayDiff(new Date("2023-06-23"), new Date("1997-05-31"))
12. 生成指定长度的随机字符串
const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')
generateRandomString(12)
generateRandomString(12)
13. 获取两个整数之间的随机整数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 100)
random(1, 100)
random(1, 100)
14. 检查元素是否处于焦点
const isFocus = (ele) => ele === document.activeElement