天天看點

18 個殺手級 JavaScript One Lines

18 個殺手級 JavaScript One Lines

英文 | https://javascript.plainenglish.io/18-killer-javascript-one-liners-%EF%B8%8F-b11f0c796024

翻譯 | 楊小二

1、複制到剪貼闆

使用 navigator.clipboard.writeText 輕松将任何文本複制到剪貼闆。

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");      

2、檢查日期是否有效

使用以下代碼段檢查給定日期是否有效。

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true      

3、找出一年中的哪一天

查找給定日期的哪一天。

const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272      

4、将字元串大寫

Javascript 沒有内置的大寫函數,是以我們可以使用以下代碼。

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more      

5、找出兩日期之間的天數

使用以下代碼段查找給定 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      

6、清除所有 Cookie

你可以通過使用 document.cookie 通路 cookie 并清除它來輕松清除存儲在網頁中的所有 cookie。

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));      

7、生成随機十六進制

你可以使用 Math.random 和 padEnd 屬性生成随機十六進制顔色。

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008      

8、從數組中删除重複項

你可以使用 JavaScript 中的 Set 輕松删除重複項。

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 ]      

9、從 URL 擷取查詢參數

你可以通過傳遞 window.location 或原始 URL goole.com?search=easy&page=3 從 url 輕松檢索查詢參數

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 }      

10、從日期記錄時間

我們可以從給定日期以小時::分鐘::秒的格式記錄時間。

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"      

11、檢查數字是偶數還是奇數

const isEven = num => num % 2 === 0;
console.log(isEven(2)); 
// Result: True      

12、求數字的平均值

使用 reduce 方法找到多個數字之間的平均值。

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

13、反轉字元串

你可以使用 split、reverse 和 join 方法輕松反轉字元串。

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// Result: 'dlrow olleh'      

14、檢查數組是否為空

檢查數組是否為空的簡單單行程式将傳回 true 或 false。

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true      

15、擷取標明的文本

使用内置的 getSelectionproperty 擷取使用者選擇的文本。

const getSelectedText = () => window.getSelection().toString();
getSelectedText();      

16、打亂數組

使用 sort 和 random 方法打亂數組非常容易。

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]      

17、檢測暗模式

使用以下代碼檢查使用者的裝置是否處于暗模式。

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False      

18、将 RGB 轉換為十六進制

const rgbToHex = (r, g, b) => 
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255); 
// Result: #0033ff      

總結

這18條非常實用的JavaScript One Lines,請你收藏好,如果有任何問題,請記得在留言區告訴我,如果你覺得今天内容對你非常有幫助,請記得分享給你身邊做開發的朋友。

最後,感謝你的時間,謝謝你的閱讀。

學習更多技能

請點選下方公衆号

繼續閱讀