19個(gè)讓你看起來像專業(yè)人士的 JavaScript 單行代碼

英文 | https://javascript.plainenglish.io/18-javascript-one-liners-thatll-make-you-look-like-a-pro-678da78ccdb0
翻譯 | 楊小愛
const randomString = () => Math.random().toString(36).slice(2)randomString() // gi1qtdego0brandomString() // f3qixv40motrandomString() // eeelv1pm3ja
2、轉(zhuǎn)義HTML特殊字符
如果您了解 XSS,其中一種解決方案是轉(zhuǎn)義 HTML 字符串。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))escape('<div class="medium">Hi Medium.</div>')// <div class="medium">Hi Medium.</div>
3、將字符串中每個(gè)單詞的第一個(gè)字符大寫
此方法用于將字符串中每個(gè)單詞的第一個(gè)字符大寫。
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())uppercaseWords('hello world'); // 'Hello World'
另外,在這里,我要謝謝克里斯托弗·斯特羅利亞-戴維斯,他還跟我分享了他的更加簡單的方法,代碼如下:
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())4、將字符串轉(zhuǎn)換為camelCase
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));toCamelCase('background-color'); // backgroundColortoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumbtoCamelCase('_hello_world'); // HelloWorldtoCamelCase('hello_world'); // helloWorld
5、刪除數(shù)組中的重復(fù)值
刪除數(shù)組的重復(fù)項(xiàng)是非常有必要的,使用“Set”會(huì)變得非常簡單。
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]
6、?展平一個(gè)數(shù)組
我們經(jīng)常在面試中受到考驗(yàn),這可以通過兩種方式來實(shí)現(xiàn)。
const flat = (arr) =>[].concat.apply([],arr.map((a) => (Array.isArray(a) ? flat(a) : a)))// Orconst flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
7、從數(shù)組中刪除虛假值
使用此方法,您將能夠過濾掉數(shù)組中的所有虛假值。
const removeFalsy = (arr) => arr.filter(Boolean)removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])// ['a string', true, 5, 'another string']
8、檢查一個(gè)數(shù)字是偶數(shù)還是奇數(shù)
超級簡單的任務(wù),可以通過使用模運(yùn)算符 (%) 來解決。
const isEven = num => num % 2 === 0isEven(2) // trueisEven(1) // false
9、獲取兩個(gè)數(shù)字之間的隨機(jī)整數(shù)
此方法用于獲取兩個(gè)數(shù)字之間的隨機(jī)整數(shù)。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)random(1, 50) // 25random(1, 50) // 34
10、獲取參數(shù)的平均值
我們可以使用 reduce 方法來獲取我們在此函數(shù)中提供的參數(shù)的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4, 5); // 3
11、將數(shù)字截?cái)酁楣潭ㄐ?shù)點(diǎn)
使用 Math.pow() 方法,可以將一個(gè)數(shù)字截?cái)酁槲覀冊诤瘮?shù)中提供的某個(gè)小數(shù)點(diǎn)。
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)round(1.005, 2) //1.01round(1.555, 2) //1.56
12、計(jì)算兩個(gè)日期相差天數(shù)
有時(shí)候我們需要計(jì)算兩個(gè)日期之間的天數(shù),一行代碼就可以搞定。
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));diffDays(new Date("2021-11-3"), new Date("2022-2-1")) // 90
13、從日期中獲取一年中的哪一天
如果我們想知道某個(gè)日期是一年中的哪一天,我們只需要一行代碼即可實(shí)現(xiàn)。
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))dayOfYear(new Date()) // 74
14、生成一個(gè)隨機(jī)的十六進(jìn)制顏色
如果你需要一個(gè)隨機(jī)的顏色值,這個(gè)函數(shù)就可以了。
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`randomColor() // #9dae4frandomColor() // #6ef10e
15、將RGB顏色轉(zhuǎn)換為十六進(jìn)制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)rgbToHex(255, 255, 255) // '#ffffff'
16、清除所有cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))17、檢測暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches18、交換兩個(gè)變量
[] = [bar, foo]19、暫停一會(huì)
const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))const fn = async () => {await pause(1000)console.log('fatfish') // 1s later}fn()
最后
以上就是我今天跟你分享的19個(gè)關(guān)于JS的單行代碼知識,希望對你有所幫助,也希望你能從中學(xué)習(xí)到一些新東西。
在此,感謝你的閱讀,如果你覺得有用,請記得點(diǎn)贊我,關(guān)注我,同時(shí)將它分享給你身邊做開發(fā)的朋友,也能能夠幫助到他。
祝編程愉快!
學(xué)習(xí)更多技能
請點(diǎn)擊下方公眾號
![]()

