redd 發表於 2022-3-25 15:54:28

常用到的 JavaScript

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

copyToClipboard("Hello World");把文字複製到剪貼簿。

redd 發表於 2022-3-25 15:57:52

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

capitalize("follow for more"); // Result: Follow for more把第一個字母轉成大寫。

redd 發表於 2022-3-25 16:03:16

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算天數。

redd 發表於 2022-3-25 16:06:18

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));清除網頁上的所有 Cookies.

redd 發表於 2022-3-25 16:09:43

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates());
// Result: [ 1, 2, 3, 4, 5, 6 ]把 Array 中重複的去掉。

redd 發表於 2022-3-25 16:14:18

const getParameters = (URL) => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
return JSON.stringify(URL);
};

getParameters(window.location);
// Result: { search : "easy", page : 3 }取出網址中的參數,例如網址是: goole.com/?search=easy&page=3

redd 發表於 2022-3-25 16:16:35

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

console.log(isEven(2));
// Result: True判斷偶數或奇數。

redd 發表於 2022-3-25 16:52:21

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

average(1, 2, 3, 4);
// Result: 2.5計算幾個數字的平均數。

redd 發表於 2022-3-25 17:04:05

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

isNotEmpty();
// Result: true檢查 Array 是不是空的?

redd 發表於 2022-3-25 17:07:21

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

getSelectedText();取得選取的文字。

redd 發表於 2022-3-25 17:15:13

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

console.log(isDarkMode);
// Result: True or FalseDetect Dark Mode: Check if a user’s device is in dark mode.
頁: [1]
查看完整版本: 常用到的 JavaScript