生成多个不包含某些数的随机数

-

主要用到while循环、还有让一个函数执行多次,先生成一个指定长度的数组,然后循环执行

例如,在0-9之间取随机整数,不包含1 、2 、3 、 4 、 5 、6 、7 、8 

let arr = [1,2,3,4,5,6,7,8];

function genarateRandom(){
  let random = Math.floor(Math.random() * 10);
  console.log(random, '首次生成');
  while(arr.includes(random)){
    random = Math.floor(Math.random() * 10);
    console.log(random, '再次生成');
  }
  return random;
}

let b = [];
new Array(3).fill(1).forEach(() => {
  b.push(genarateRandom())
});
console.log(b); // [9,0,9]

-

原文地址:https://www.cnblogs.com/fqh123/p/15489481.html