本文为转载翻译文章
原文地址:https://dev.to/saviomartin/20-killer-javascript-one-liners-94f
原文作者:Savio Martin
今天分享20个令人惊艳的一行JavaScript代码,让你写bug更轻松。走你。🚀
获取浏览器Cookie的值
通过访问document.cookie来获取需要的Cookie的值。
1 2 3 4
| const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
|
把RGB转换成十六进制(hex)
1 2 3 4
| const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255);
|
复制到剪贴板
通过使用navigator.clipboard.writeText轻松地将任何文本复制到剪贴板。
1 2 3
| const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
|
检查日期是否有效
使用以下代码片段检查给定日期是否有效。
1 2 3 4
| const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
|
查找一年中的某一天
查找给定日期是哪一天。
1 2 3 4 5
| const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
|
将字符串首字母大写
Javascript 没有内置的大写函数,因此我们可以使用以下代码来实现此目的。
1 2 3 4
| const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
|
查找两天之间间隔天数
使用以下代码片段查找2个给定日期之间的间隔天数。
1 2 3 4
| const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
|
清除所有 Cookie
你可以通过使用 document.cookie 访问 cookie 并清除它,轻松清除存储在网页中的所有 cookie。
1
| const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
|
生成随机十六进制
你可以使用 Math.random 和 padEnd 属性生成随机十六进制颜色。
1 2 3 4
| const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
|
数组去重
你可以使用 JavaScript 中的 Set 轻松删除重复项。 简直🐮🍺。
1 2 3 4
| const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
|
获取地址栏参数
通过 window.location 或原始 URL 轻松查询 goole.com?search=easy&page=3 的参数。
1 2 3 4 5 6 7
| const getParameters = (URL) => { URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}'); return JSON.stringify(URL); };
getParameters(window.location)
|
从日期获取“时分秒”格式的时间
我们可以从日期中,获取到 hour : minutes : seconds 格式的时间:
1 2 3 4
| const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
|
判断数字奇偶
1 2 3 4
| const isEven = num => num % 2 === 0;
console.log(isEven(2));
|
求平均值
使用 reduce 方法找到多个数字的平均值。
1 2 3
| const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4);
|
返回顶部
使用 window.scrollTo(0, 0) 方法自动回到顶部。将 x 和 y 都设置为 0。
1 2
| const goToTop = () => window.scrollTo(0, 0); goToTop();
|
翻转字符串
使用split,reverse 和 join 方法轻松翻转字符串。
1 2 3
| const reverse = str => str.split('').reverse().join(''); reverse('hello world');
|
检查数组是否为空
检查数组是否为空的简单代码,结果将返回 true 或 false。
1 2 3 4
| const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
|
获取选定的文本
使用内置的 getSelection 属性获取用户选择的文本。
1 2
| const getSelectedText = () => window.getSelection().toString(); getSelectedText();
|
打乱数组
使用 sort 和 random 方法对数组进行打乱混合。
1 2 3
| const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4]));
|
检测用户是否处于暗模式
使用以下代码检查用户的设备是否处于暗模式。
1 2 3
| const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
|