Random 使用

一、生成随机颜色

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

持续更新中...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值