英文 | https://blog.devgenius.io/15-javascript-codes-you-will-always-need-e8569903dd1
翻譯 | 楊小愛
01、打亂數組
使用 sort 和 random 方法打亂數組非常容易。
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
02、檢查日期是否有效
使用以下代碼段檢查給定日期是否有效。
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true
03、複制到剪貼闆
使用 navigator.clipboard.writeText 輕松将任何文本複制到剪貼闆。
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
04、找出一年中指定那一天
找出給定日期的哪一天。
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272
05、将字元串大寫
Javascript 沒有内置的大寫函數,是以我們可以為此使用以下代碼。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more
06、找出兩個日期之間的天數
使用以下代碼段查找給定 日期之間的天數。
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
07、清除所有 Cookie
您可以通過使用 document.cookie 通路 cookie 并清除它來輕松清除存儲在網頁上的所有 cookie。
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
08、生成随機十六進制
您可以使用 Math.random 和 padEnd 屬性生成随機的十六進制顔色。
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008
09、從數組中删除重複項
您可以使用 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 ]
10、從 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 }
11、從日期記錄時間
我們可以從給定日期以小時::分鐘::秒的格式記錄時間。
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"
12、檢查數字是偶數還是奇數
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
13、求數字的平均值
使用reducemethod求多個數字之間的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
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、檢測暗模式
使用以下代碼檢查使用者的裝置是否處于暗模式。
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
全文完~