极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
每天晚上九点 B站讲解前端工程化直播,并解答相关问题。

# 随机生成六位数的手机验证码(重复/不可重复)

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 663 (opens new window)

const random = (n) => Math.floor(Math.random() * (n + 1));

// 可生成重复的随机验证码
function randomCode() {
  return [0, 0, 0, 0, 0, 0].map(() => random(9));
}

// 不可生成重复的随机验证码
const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5);
const randomUniqueCode = () =>
  shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).slice(0, 6);

// 一种比较低效的解法
function randomUniqueCode2() {
  let i = 0;
  let l = [];
  while (i < 6) {
    const x = random(9);
    if (!l.includes(x)) {
      i++;
      l.push(x);
    }
  }
  return l;
}

// 不可重复

const numArr = [];
while (numArr.length < 6) {
  let num = parseInt(Math.random() * 10);
  if (numArr.indexOf(num) === -1) {
    numArr.push(num);
  }
}
function sample(length) {
  let arr = Array(100)
    .fill(1)
    .map((_, i) => (i / 10) | 0);
  return shuffle(arr, length);
}

function notSample(length) {
  let arr = Array(10)
    .fill(1)
    .map((_, i) => i);
  return shuffle(arr, length);
}

function shuffle(arr, length) {
  let index = 0;
  while (index < length) {
    let changeIndex = arr.length - 1 - index;
    let randomIndex = Math.round(Math.random() * (changeIndex - 1));
    let temp = arr[changeIndex];
    arr[changeIndex] = arr[randomIndex];
    arr[randomIndex] = temp;
    index += 1;
  }
  return arr.slice(arr.length - length).join("");
}
Last Updated: 11/27/2021, 10:11:48 AM