一、生成随机颜色
const getRandomColor = () =>
`#${Math.random().toString(16).slice(2, 8).padEnd(6, "0")}`;
// console.log(getRandomColor()); // #f7668d
const getRandomColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
// console.log(getRandomColor()); // '#4c2fd7'
二、生成制定长度随机字符串
const randomString = (len = 6, rep = "0") => {
if (len <= 11) {
return Math.random()
.toString(36)
.slice(2, 2 + len)
.padEnd(len, rep);
} else {
return randomString(11, rep) + randomString(len - 11, rep);
}
};
// console.log(randomString(134)); // i8p56ovav60g8xfdlyxtlau6d1zuj1tz0xd8ucndr20nchw6p7jpo5kmogb8yo75lo32pj7m2cw3yifv3fjxhwepvuh6xh3u27ahtr3w5nggb9gxhia5su910x2d3rvomqgsh9
三、打乱数组顺序
const randomSort = (list) => list.sort(() => Math.random() - 0.5);
const arrSort = randomSort([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// console.log(arrSort); // [9, 4, 3, 2, 7, 1, 5, 6, 0, 8]
四、随机 IP 地址
const randomIp = () =>
Array(4)
.fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join(".");
// console.log(randomIp()); 223.123.181.65
五、生成 UUID
const uuid = (a) =>
a
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
// console.log(uuid()); // 55d319d7-b14c-46c1-bc3b-2ab891f1b170
持续更新中...