天天看點

18 個讓你看起來像專業人士的 JavaScript 單行代碼

18 個讓你看起來像專業人士的 JavaScript 單行代碼

今天,我将跟大家分享18個JS的單行代碼技巧,這些技巧都是平時工作和閱讀時候收集起來的,經過在實際項目中的應用,我覺得還是非常不錯,并且還可以提升我們的開發效率,建議你也收藏起來,以便後面需要的時候,可以直接使用。

現在,我們就開始今天的内容吧,希望通過閱讀這篇文章,可以幫助你提升 JS 知識和技能。

1、生成随機字元串

我們可以使用 Math.random 生成一個随機字元串,當我們需要一個唯一的 ID 時非常友善。

const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja      

2、轉義HTML特殊字元

如果您了解 XSS,其中一種解決方案是轉義 HTML 字元串。

const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
escape('<div class="medium">Hi Medium.</div>') 
// <div class="medium">Hi Medium.</div>      

3、字元串中每個單詞的第一個字元大寫

此方法用于将字元串中每個單詞的第一個字元大寫。

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、将字元串轉換為camelCase

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld      

5、删除數組中的重複值

删除數組的重複項是非常有必要的,使用“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]      

6、展平一個數組

我們經常在面試中受到考驗,這可以通過兩種方式來實作。

const flat = (arr) =>
    [].concat.apply(
        [],
        arr.map((a) => (Array.isArray(a) ? flat(a) : a))
    )
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']      

7、從數組中删除虛假值

使用此方法,您将能夠過濾掉數組中的所有虛假值。

const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']      

8、檢查一個數字是偶數還是奇數

超級簡單的任務,可以通過使用模運算符 (%) 來解決。

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

9、擷取兩個數字之間的随機整數

此方法用于擷取兩個數字之間的随機整數。

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34      

10、擷取參數的平均值

我們可以使用 reduce 方法來擷取我們在此函數中提供的參數的平均值。

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

11、将數字截斷為固定小數點

使用 Math.pow() 方法,我們可以将一個數字截斷為我們在函數中提供的某個小數點。

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56      

12、計算兩個日期相差天數

有時候我們需要計算兩個日期之間的天數,一行代碼就可以搞定。

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、從日期中擷取一年中的哪一天

您想知道某個日期是一年中的哪一天嗎?

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74      

14、生成一個随機的十六進制顔色

如果你需要一個随機的顔色值,這個函數就可以了。

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e      

15、将RGB顔色轉換為十六進制

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)').matches      

18、交換兩個變量

[foo, bar] = [bar, foo]      

19、暫停一會

const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
  await pause(1000)
  console.log('fatfish') // 1s later
}
fn()      

總結

以上就是今天分享的所有單行代碼技巧,感謝你的閱讀,祝程式設計愉快!

學習更多技能

請點選下方公衆号