为了提高你的起像 JavaScript 知识与技能,你应该了解一些JavaScript的个J个专单行代码技巧。
为了提高网站的杀手级士用户体验,我们经常需要将内容复制到剪贴板,语句业人以便用户粘贴到指定的起像地方。
const copyToClipboard = (content) => navigator.clipboard.writeText(content)copyToClipboard("Hello fatfish")
您以前遇到过这种情况吗?
我们需要获取用户选择的个J个专内容。
const getSelectedText = () => window.getSelection().toString()getSelectedText()
打乱数组?这在彩票项目中很常见,杀手级士但它并不是语句业人真正随机的。
const shuffleArray = array => array.sort(() => Math.random() - 0.5)shuffleArray([ 1,起像 2,3,4, -1, 0 ]) // [3, 1, 0, 2, 4, -1]
我们可以将 RGBA 和十六进制颜色值相互转换。
const rgbaToHex = (r,个J个专 g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')rgbaToHex(0, 0 ,0) // #000000rgbaToHex(255, 0, 127) //#ff007f
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)
使用reduce我们可以非常方便的得到一组数组的平均值。
const average = (...args) => args.reduce((a,杀手级士 b) => a + b, 0)average(0, 1, 2, -1, 9, 10) // 3.5
如何判断一个数是奇数还是偶数?
const isEven = num => num % 2 === 0isEven(2) // trueisEven(1) // false
要删除数组中的重复元素,使用 Set 将变得非常容易。语句业人
const uniqueArray = (arr) => [...new Set(arr)]uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ]) // [1, 2, 3, 4, 5, -1, 0]
判断一个对象是否为空容易吗?
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === ObjectisEmpty({ }) // trueisEmpty({ name: 'fatfish' }) // false
const reverseStr = str => str.split('').reverse().join('')reverseStr('fatfish') // hsiftaf
const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519
今天是2023年6月23日,那么今年是什么日子呢?
const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)dayInYear(new Date('2023/06/23'))// 174
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("hello fatfish") // Hello fatfish
const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')generateRandomString(12) // cysw0gfljoyxgenerateRandomString(12) // uoqaugnm8r4s
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)random(1, 100) // 27random(1, 100) // 84random(1, 100) // 55
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)round(3.1415926, 3) //3.142round(3.1415926, 1) //3.1
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${ new Date(0).toUTCString()};path=/`))
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matchesconsole.log(isDarkMode)
const goToTop = () => window.scrollTo(0, 0)goToTop()
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform)isAppleDevice()
const randomBoolean = () => Math.random() >= 0.5randomBoolean()
const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()typeOf('') // stringtypeOf(0) // numbertypeOf() // undefinedtypeOf(null) // nulltypeOf({ }) // objecttypeOf([]) // arraytypeOf(0) // numbertypeOf(() => { }) // function
const checkTabInView = () => !document.hidden
const isFocus = (ele) => ele === document.activeElement
const generateRandomIP = () => { return Array.from({ length: 4}, () => Math.floor(Math.random() * 256)).join('.');}generateRandomIP() // 220.187.184.113generateRandomIP() // 254.24.179.151
以上就是我今天想与你分享的25个关于JavaScript的单行代码技巧。如果你觉得有用的话,请记得点赞我关注我。
最后,感谢你的阅读。
责任编辑:华轩 来源: web前端开发 JavaScrip技能(责任编辑:百科)
中国海油牵头签订国内最大规模液化天然气船舶建造项目 建造金额约160亿元
赛生药业(06600.HK)年度实现纯利7.5亿元 每股基本盈利约为人民币1.38元
GMIC北京2017大会今日开幕 以“天·工·开·悟”探索科学复兴
日式RPG《星之海》steam体验版上线 8月30日全平台发售
中欧班列(西安)2021年累计运输车数突破3万车 同比增长24.36%