随机十六进制颜色生成器
// 方法1
const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
// 方法2
const generateRandomHexColor = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padStart(6, '0')}`
生成随机RGBA
const generateRandomRGBA = () => {
const r = Math.floor(Math.random() * 256)
const g = Math.floor(Math.random() * 256)
const b = Math.floor(Math.random() * 256)
const a = Math.random().toFixed(2)
return `rgba(${[ r, g, b, a ].join(',')})`
}
RGBA 和十六进制颜色值相互转换
// rgba 转 十六进制
const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')
rgbaToHex(0, 0 ,0) // #000000
rgbaToHex(255, 0, 127) //#ff007f
// 十六进制 转 rgba
const hexToRgba = hex => {
const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
return `rgba(${r}, ${g}, ${b}, 1)`;
}
hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)
随机数生成器
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
生成介于最大最小值的随机数
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
两个日期之间的天数
const daysBetweenDates = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));
检查日期是否是周末
const isWeekend = (date) => [5, 6].indexOf(date.getDay()) !== -1;
深拷贝一个对象
const obj = {
name: 'fatfish',
node: {
name: 'medium',
node: {
name: 'blog'
}
}
}
const cloneObj = structuredClone(obj)
cloneObj.name = '1111'
cloneObj.node.name = '22222'
console.log(cloneObj)
/*
{
"name": "1111",
"node": {
"name": "22222",
"node": {
"name": "blog"
}
}
}
*/
console.log(obj)
/*
{
"name": "fatfish",
"node": {
"name": "medium",
"node": {
"name": "blog"
}
}
}
*/
获取当前选中的文本
const getSelectedContent = () => window.getSelection().toString()
生成指定长度的字符串
const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')
generateRandomString(8)
获取 HH:MM:SS 格式的当前时间
const currentTime = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
currentTime()
从数组中删除假值
let arr = [12, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
let filterArray = arr.filter(Boolean);
// filterArray ===> [12, 'xyz', -25, 0.5]
按位 NOT (~) 运算符
// !~ 运算符对于 -1 为true, 其他为false
!~-1 // true
!~xxx // false
双位NOT运算符
//双位NOT运算符 ~~ , 可以用来代替Math.floor() 函数
console.log(Math.floor(9.5)) // 9
console.log(~~9.5) // 9
指数运算符
Math.pow(2,3); // 8
// 简化写法
2**3 // 8
空值合并运算符 ?? 和 空合并赋值运算符 ??=
// 空合并运算符
let person1 = 'Bob';
let person2 = null;
let test1= person1 ?? 'Jack'; // log(test1) 'Bob'
let test2= person2 ?? 'Jack'; // log(test2) 'Jack'
// 空合并赋值运算符
let person1 = null;
let person2 = "Bob";
person1 ??= person2; // log(person1, person2) "Bob" "Bob"