20個殺手級 JavaScript 單行代碼

01、獲取瀏覽器Cookie的值
通過document.cookie 來查找cookie值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();cookie('_ga');// Result: "GA1.2.1929736587.1601974046"
02、顏色RGB轉(zhuǎn)十六進制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);rgbToHex(0, 51, 255);// Result: #0033ff
03、復(fù)制到剪貼板
借助navigator.clipboard.writeText可以很容易的講文本復(fù)制到剪貼板
規(guī)范要求在寫入剪貼板之前使用 Permissions API 獲取“剪貼板寫入”權(quán)限。但是,不同瀏覽器的具體要求不同,因為這是一個新的API。有關(guān)詳細信息,請查看compatibility table and Clipboard availability in Clipboard。
const copyToClipboard = (text) => navigator.clipboard.writeText(text);copyToClipboard("Hello World");
04、檢查日期是否合法
使用以下代碼段檢查給定日期是否有效。
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());isDateValid("December 17, 1995 03:24:00");// Result: true
05、查找日期位于一年中的第幾天
const dayOfYear = (date) =>Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);dayOfYear(new Date());// Result: 272
06、英文字符串首字母大寫
JavaScript沒有內(nèi)置的首字母大寫函數(shù),因此我們可以使用以下代碼。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("follow for more")// Result: Follow for more
07、計算2個日期之間相差多少天
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)dayDif(new Date("2020-10-21"), new Date("2021-10-22"))// Result: 366
08、清除全部Cookie
通過使用document.cookie訪問cookie并將其清除,可以輕松清除網(wǎng)頁中存儲的所有cookie。
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
09、生成隨機十六進制顏色
可以使用 Math.random 和 padEnd 屬性生成隨機的十六進制顏色。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;console.log(randomHex());// Result: #92b008
10、數(shù)組去重
可以使用 JavaScript 中的Set輕松刪除重復(fù)項
const removeDuplicates = (arr) => [...new Set(arr)];console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));// Result: [ 1, 2, 3, 4, 5, 6 ]
11、從 URL 獲取查詢參數(shù)
可以通過傳遞 window.location 或原始 URL goole.com?search=easy&page=3 輕松地從 url 檢索查詢參數(shù)
const getParameters = (URL) => {URL = jsON.parse('{"' +decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');return jsON.stringify(URL);};getParameters(window.location);// Result: { search : "easy", page : 3 }
或者更為簡單的:
Object.fromEntries(new URLSearchParams(window.location.search))// Result: { search : "easy", page : 3 }
12、時間處理
我們可以從給定日期以 hour::minutes::seconds 格式記錄時間。
const timeFromDate = date => date.toTimeString().slice(0, 8);console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));// Result: "17:30:00"
13、校驗數(shù)字是奇數(shù)還是偶數(shù)
const isEven = num => num % 2 === 0;console.log(isEven(2));// Result: True
14、求數(shù)字的平均值
使用reduce方法找到多個數(shù)字之間的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);// Result: 2.5
15、回到頂部
可以使用 window.scrollTo(0, 0) 方法自動滾動到頂部。將 x 和 y 都設(shè)置為 0。
const goToTop = () => window.scrollTo(0, 0);goToTop();
16、翻轉(zhuǎn)字符串
可以使用 split、reverse 和 join 方法輕松反轉(zhuǎn)字符串。
const reverse = str => str.split('').reverse().join('');reverse('hello world');// Result: 'dlrow olleh'
17、校驗數(shù)組是否為空
一行代碼檢查數(shù)組是否為空,將返回true或false
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;isNotEmpty([1, 2, 3]);// Result: true
18、獲取用戶選擇的文本
使用內(nèi)置的getSelection 屬性獲取用戶選擇的文本。
const getSelectedText = () => window.getSelection().toString();getSelectedText();
19、打亂數(shù)組
可以使用sort 和 random 方法打亂數(shù)組
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());console.log(shuffleArray([1, 2, 3, 4]));// Result: [ 1, 4, 3, 2 ]
20、檢查用戶的設(shè)備是否處于暗模式
使用以下代碼檢查用戶的設(shè)備是否處于暗模式。
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matchesconsole.log(isDarkMode)// Result: True or False
學(xué)習(xí)更多技能
請點擊下方公眾號
![]()

評論
圖片
表情
