20個(gè)嘆為觀止的JavaScript一行代碼

1、獲取瀏覽器cookie值

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

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


2、將RGB轉(zhuǎn)換為16進(jìn)制

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

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


3、復(fù)制到剪切板(使用 navigator.clipboard.writeText 輕松將任何文本復(fù)制到剪貼板上)

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

copyToClipboard("Hello World");


4、檢查日期是否有效

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

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


5、找出一年中的某一天(即給出一個(gè)日期,程序給出屬于本年的第多少天)

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

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

6、將字符串首字母大寫

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

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


7、計(jì)算兩個(gè)日期之間相差的天數(shù)

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


8、清除所有cookie

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


9、生成隨機(jī)16進(jìn)制

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

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


10、數(shù)組去重

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ù)

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 }


12、從日期中獲取“時(shí)分秒”格式的時(shí)間

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"


13、確認(rèn)奇偶數(shù)

//通過數(shù)據(jù)%2來判斷并返回布爾類型
const isEven = num => num % 2 === 0;

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


14、求平值

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

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


15、回到頂部(適用于網(wǎng)頁右下角快捷返回功能)

//通過將x、y設(shè)置為0來實(shí)現(xiàn)
const goToTop = () => window.scrollTo(0, 0);

goToTop();


16、反轉(zhuǎn)字符串

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

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


17、檢查數(shù)組是否為空

//通過對(duì)數(shù)組長度判斷來確定是否為空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

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


18、獲取用戶選定的文本

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

getSelectedText();


19、打亂數(shù)組

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

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


20、檢查用戶是否處于暗模式

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

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


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容