跳到主要内容

其他

One-Liner​

随机数生成器​

// 生成 [min, max] 范围内的随机整数
const randomNumber = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);

随机十六进制颜色生成器​

const randomHexColor = () =>
`#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

随机布尔生成器​

const randomBoolean = () => Math.random() >= 0.5;

检查数组是否为空​

const isEmpty = arr => !Array.isArray(arr) || !arr.length;

检查数组是否包含值​

const includes = (arr, value) => arr.indexOf(value) != -1;
// or
const includes = (arr, value) => arr.includes(value);

检查日期是否是周末​

// getDay():0 是周日,6 是周六
const isWeekend = date => [0, 6].indexOf(date.getDay()) !== -1;

复制到剪贴板​

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

// Testing
copyToClipboard('Hello World!');

检测深色模式​

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

// Testing
console.log(isDarkMode());