极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

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

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("");
}

//可重复的 function liunum() { let yanzheng = '' for (let i = 0; i < 6; i++) { let num = Math.floor(Math.random()*10) yanzheng += num } return yanzheng } let num = liunum() console.log('重复的',num); //不可重复的 function liunum1() { let yanzheng1 = '' for (let j = 0; j < 6; j++) { let num1 = Math.floor(Math.random()*10) if (yanzheng1.indexOf(num1)==-1)yanzheng1 += num1 else j--; } return yanzheng1 } let num1 = liunum1() console.log('不重复的',num1);

const randTo = (n: number) => ~~(Math.random() * (n + 1));

const shuffle = (list: Array<any>) => list.sort(() => Math.random() - 0.5);

// 随机生成六位数的手机验证码(重复/不可重复)
const vc = ({ len = 6, repeat = true } = {}) => {
  if (len > 10 && repeat === false) {
    throw new Error("len should less equal than 10 if repeat is false");
  }
  if (repeat) {
    return Array(len)
      .fill(0)
      .map(() => randTo(9));
  } else {
    return shuffle([...Array(10).keys()]).slice(0, len);
  }
};

console.log(vc());
console.log(vc({ len: 9 }));
console.log(vc({ repeat: false }));
console.log(vc({ len: 9, repeat: false }));
console.log(vc({ len: 11, repeat: false }));
const random = (length) => Math.floor(Math.random() * length);

// 重复
const randomCode = () => {
  return [...new Array(6)].map((i) => random(10));
};

// 不重复
const randomUniqueCode = () => {
  let arr = [...new Array(10)].map((_, index) => index);
  return [...new Array(6)].map((i) => {
    const selectIndex = random(arr.length);
    return arr.splice(selectIndex, 1)[0];
  });
};
Last Updated: 4/27/2022, 11:56:45 AM