JavaScript 单行代码知识技能

78 阅读1分钟

1.复制内容到剪贴板

const copyToClipboard = (content) => navigator.clipboard.writeText(content)
copyToClipboard("Hello world")

2.获取鼠标选中内容

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

3.打乱数组

const shuffleArray = array => array.sort(() => Math.random() - 0.5)
shuffleArray([ 1, 2, 3, 4, 5, 6, 7 ]) // [7, 5, 2, 6, 3, 4, 1]

4.将 rgb 转换为十六进制

const rgbToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')

rgbToHex(0, 0, 0) // #000000
rgbToHex(255, 0, 147) // #ff0093

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') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.获取多个数字的平均值

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length
average(0, 1, 2, 1, 2, 3, 4, 5, 6, 7) // 3.1

7.检查数字是偶数还是奇数

const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false

8.删除数组中的重复元素

const uniqueArray = (arr) => [...new Set(arr)]
uniqueArray([ 0, 1, 2, 1, 2, 3, 4, 5, 6, 7 ]) // [0, 1, 2, 3, 4, 5, 6, 7]

9.检查对象是否为空对象

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
isEmpty({}) // true
isEmpty({ name: 'isEmpty' }) // false

10.反转字符串

const reverseStr = str => str.split('').reverse().join('')
reverseStr('reverseStr') // rtSesrever

11.计算两个日期之间的间隔天数

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)
dayDiff(new Date("2023-02-23"), new Date("2024-09-09")) // 444

12.找出日期所在的年份的天数

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
dayInYear(new Date('2024/09/09')) // 253

13.字符串的首字母大写

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world")  // Hello world

14.生成指定长度的随机字符串

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')
generateRandomString(32) // 951slnznnymewyvrfpcbndkqqqanyj0m

15.获取两个整数之间的随机整数

const random = (min, max) => Math.floor(Math.random() * (max - min) + min)
random(1, 100) // 41,包含左边、不包含右边

16.清除所有 cookie

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

17.检测是否为暗模式

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

18.滚动到页面顶部

// 方法一
const goToTop = () => window.scrollTo(0, 0)
// 方法二,平滑滚动
const goToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });

goToTop()

19.确定是否为 Apple 设备

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform)
isAppleDevice()  // false

20.随机布尔值

const randomBoolean = () => Math.random() >= 0.5
randomBoolean()   // true

21.确定当前浏览器选项卡是否处于显示状态

const checkTabInView = () => !document.hidden
checkTabInView()  // true