使用这些单行代码,节约您的编码时间。
查找数组中的最大值
Math.max(...[2,1,3])
查找数组最小值
Math.min(...[2,1,3])
检查字符串是否为有效数字
!isNaN(parseFloat('1.0'))
获取当前日期和时间
new Date().toString() // Wed Feb 01 2023 01:07:08 GMT+0800 (中国标准时间)
检查一个变量是否为对象
typeof {} === 'object' //true
typeof null === 'object' //注意 typeof null 也返回true
将数组转换为字符串
[1,2,3].join(',') //'1,2,3'
计算数组中某个元素的出现次数
[1,2,1,3].filter(x => x === 1).length //2
检查字符串是否为回文
'121' === '121'.split('').reverse().join('') //true
使用动态键和值创建一个新对象
{[key]: value}
获取数组中所有数字的总和
[1,2,3,4].reduce((a,b) => a + b, 0)
获取当前时间戳
Date.now()
检查变量是否为null、undefined
variable === null
variable === undefined
或
typeof variable === 'undefined'
创建一个具有指定范围数字的新数组
Array.from({length: n}, (_, I) => I) //[0, 1, 2]
Array.from({length: 3}, (_, I) => I+1) //[1, 2, 3]
生成一个1到100之间的随机数
Math.floor(Math.random() * 100) + 1 // 29
删除数组中的重复项
可以使用 JavaScript 中的Set轻松删除重复项
[...new Set([1,2,1,1,2,3])] //[1, 2, 3]
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 ]
获取浏览器Cookie的值
通过document.cookie 来查找cookie值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.628042602.1656670337"
颜色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可以很容易的将文本复制到剪贴板
规范要求在写入剪贴板之前使用 Permissions API 获取“剪贴板写入”权限。但是,不同浏览器的具体要求不同,因为这是一个新的API。
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
查找日期位于一年中的第几天
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 32
英文字符串首字母大写
Javascript没有内置的首字母大写函数,因此我们可以使用以下代码。
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world!")
// Result: Hello world!
计算2个日期之间相差多少天
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2023-01-21"), new Date("2023-02-01"))
// Result: 11
清除全部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: #296483
从 URL 获取查询参数
可以通过传递 window.location 或原始 URL goole.com?search=easy&page=3 轻松地从 url 检索查询参数
const getParameters = (URL) => {
let tempStr = decodeURI(URL.split("?")[1] || "")
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"');
if(!tempStr){
return {}
}
return JSON.parse(
'{"' +
tempStr +
'"}'
);
};
getParameters(window.location.href);
// Result: { a : "1", b: 3 }
或者更为简单的:
Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { a : "1", b: 3 }
校验数字是奇数还是偶数
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) 方法自动滚动到顶部。 将 x 和 y 都设置为 0。
const goToTop = () => window.scrollTo(0, 0);
goToTop();
校验数组是否为空
一行代码检查数组是否为空,将返回true或false
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
获取用户选择的文本
使用内置的getSelection 属性获取用户选择的文本。
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
打乱数组
可以使用sort 和 random 方法打乱数组
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
时间,节约一点是一点~