19個殺手級 JavaScript 單行程式碼,讓你看起來像專業人士
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'
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()
最後
以上就是我今天跟你分享的19個JavaScript的單行程式碼,希望對你有用,如果你覺得有幫助的話,請點讚我,關注我,並與你的開作者朋友分享這篇文章,最後,感謝你的閱讀,祝程式設計愉快!
「其他文章」
- Spring中實現非同步呼叫的方式有哪些?
- 帶引數的全型別 Python 裝飾器
- 整理了幾個Python正則表示式,拿走就能用!
- SOLID:開閉原則Go程式碼實戰
- React中如何引入CSS呢
- 一個新視角:前端框架們都卷錯方向了?
- 編碼中的Adapter,不僅是一種設計模式,更是一種架構理念與解決方案
- 手寫程式語言-遞迴函式是如何實現的?
- 一文搞懂模糊匹配:定義、過程與技術
- 新來個阿里 P7,僅花 2 小時,做出一個多執行緒永動任務,看完直接跪了
- Puzzlescript,一種開發H5益智遊戲的引擎
- @Autowired和@Resource到底什麼區別,你明白了嗎?
- CSS transition 小技巧!如何保留 hover 的狀態?
- React如此受歡迎離不開這4個主要原則
- LeCun再炮轟Marcus: 他是心理學家,不是搞AI的
- Java保證執行緒安全的方式有哪些?
- 19個殺手級 JavaScript 單行程式碼,讓你看起來像專業人士
- Python 的"self"引數是什麼?
- 別整一坨 CSS 程式碼了,試試這幾個實用函式
- 再有人問你什麼是MVCC,就把這篇文章發給他!