一行程式碼可以做到很多事。這邊有20個小任務都用一行就可以完成,給您參考!

  • 原文出處:https://dev.to/saviomartin/20-killer-javascript-one-liners-94f

獲取瀏覽器 Cookie 的值

讀取 document.cookie 來查 cookie 的值

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

將 RGB 轉換為十六進制

const rgbToHex = (r, g, b) =>
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255);
// Result: #0033ff

複製到剪貼板

使用 navigator.clipboard.writeText 輕鬆將任何文字複製到剪貼板。

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

copyToClipboard("Hello World");

檢查日期是否有效

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

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");
// Result: true

查找一年中的第幾天

根據給定日期,找出是第幾天。

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

dayOfYear(new Date());
// Result: 272

將字串開頭大寫

Javascript 沒有內建的 capitalize 函數。我們可以使用以下程式碼來完成。

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more

求兩天之間的天數

使用以下程式碼查找 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

清除所有 Cookie

透過 document.cookie 存取 cookie 並清除它,就可輕鬆清除網頁中的所有 cookie。

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

生成隨機十六進制顏色碼

使用“Math.random”和“padEnd”屬性,生成隨機的十六進制顏色碼。

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

console.log(randomHex());
// Result: #92b008

從陣列中刪除重複項

使用 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 ]

從 URL 獲取查詢參數

您可以從 window.location 或原始 URL goole.com?search=easy&page=3 中輕鬆找出查詢參數

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 }

把日期物件轉成時間

把日期物件以“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"

檢查數字是偶數還是奇數

const isEven = num => num % 2 === 0;

console.log(isEven(2));
// Result: True

求數的平均值

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

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5

滾動到頂部

您可以使用 window.scrollTo(0, 0) 方法自動滾動到頂部。將 xy 都設為 0。

const goToTop = () => window.scrollTo(0, 0);

goToTop();

反轉字串

您可以使用 splitreversejoin 方法輕鬆反轉字串。

const reverse = str => str.split('').reverse().join('');

reverse('hello world');
// Result: 'dlrow olleh'

檢查陣列是否為空

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true

取得選中的文字

使用內建的 getSelection 屬性取得用戶選取中的文字。

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

getSelectedText();

打亂陣列

使用 sortrandom 方法打亂陣列。

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

檢測深色模式

使用以下程式碼,檢查用戶的設備是否處於深色模式。

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

希望這些程式碼,有給您一些靈感!


共有 0 則留言