本文最后更新于 2024-04-17,文章内容可能已经过时。

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
<p>cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

2、将 RGB 转换为十六进制

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);</p>
<p>rgbToHex(0, 51, 255);
// Result: #0033ff<code></code></pre><h2 style="" id="3%E3%80%81%E5%A4%8D%E5%88%B6%E5%88%B0%E5%89%AA%E8%B4%B4%E6%9D%BF">3、复制到剪贴板</h2><pre><code>const copyToClipboard = (text) =&gt; navigator.clipboard.writeText(text); copyToClipboard("Hello World"); </code></pre><h2 style="" id="4%E3%80%81%E6%A3%80%E6%9F%A5%E6%97%A5%E6%9C%9F%E6%98%AF%E5%90%A6%E6%9C%89%E6%95%88">4、检查日期是否有效</h2><pre><code>const isDateValid = (...val) =&gt; !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // Result: true </code></pre><h2 style="" id="5%E3%80%81%E6%89%BE%E5%87%BA%E4%B8%80%E5%B9%B4%E4%B8%AD%E7%9A%84%E6%9F%90%E4%B8%80%E5%A4%A9">5、找出一年中的某一天</h2><pre><code>const dayOfYear = (date) =&gt; Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // Result: 272 </code></pre><h2 style="" id="6%E3%80%81%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%A6%96%E5%AD%97%E6%AF%8D%E5%A4%A7%E5%86%99">6、字符串首字母大写</h2><pre><code>const capitalize = str =&gt; str.charAt(0).toUpperCase() + str.slice(1) capitalize("follow for more") // Result: Follow for more </code></pre><h2 style="" id="7%E3%80%81%E8%AE%A1%E7%AE%97%E4%B8%A4%E5%A4%A9%E4%B9%8B%E9%97%B4%E7%9B%B8%E5%B7%AE%E7%9A%84%E5%A4%A9%E6%95%B0">7、计算两天之间相差的天数</h2><pre><code>const dayDif = (date1, date2) =&gt; Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2020-10-21"), new Date("2021-10-22")) // Result: 366 </code></pre><h2 style="" id="8%E3%80%81%E6%B8%85%E9%99%A4%E6%89%80%E6%9C%89-cookie">8、清除所有 Cookie</h2><pre><code>const clearCookies = document.cookie.split(';').forEach(cookie =&gt; document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/,=;expires=${new Date(0).toUTCString()};path=/)); </code></pre><h2 style="" id="9%E3%80%81%E7%94%9F%E6%88%90%E9%9A%8F%E6%9C%BA%E5%8D%81%E5%85%AD%E8%BF%9B%E5%88%B6">9、生成随机十六进制</h2><pre><code>const randomHex = () =&gt;#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008

10、数组去重

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 获取查询参数

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 }</p>
<p>/---------------or-------------/</p>
<p>Object.fromEntries(new URLSearchParams(window.location.search))

12、从日期获取“时分秒”格式的时间

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

13、确认奇偶数

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
/---------------------or----------------/
const isEven = num => (num & 1) === 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、回到顶部

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

16、翻转字符串

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

17、检查数组是否为空

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

18、获取用户选定的文本

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

19、打乱数组

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