/**
* Returns a random integer between min (inclusive) and max (inclusive).
* Pass all values as an array, as 3rd argument which values shouldn't be generated by the function.
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
const minimum = Math.ceil(min);
const maximum = Math.floor(max);
return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
}
function getRandomIntExcludingExistingNumbers(min, max, excludeArrayNumbers) {
let randomNumber;
if(!Array.isArray(excludeArrayNumbers)) {
randomNumber = getRandomInt(min, max);
return randomNumber;
}
do {
randomNumber = getRandomInt(min, max);
} while ((excludeArrayNumbers || []).includes(randomNumber));
return randomNumber;
}
const randomNumber = getRandomIntExcludingExistingNumbers(1, 10, [1, 2, 4, 5, 9]);
// 它将返回 1 到 10 之间的随机整数,不包括 1,2,4,5,9
解释:
getRandomInt 函数生成介于最小值和最大值之间的随机数。
我正在利用该函数创建“getRandomIntExcludingExistingNumbers”函数以避免特定值。
我们将简单地调用 getRandomInt(min, max) 值。
然后在 do while 循环中,我们将检查随机生成的值是否属于任何不应生成的值。
如果它是唯一的整数排除值之外,那么我们将返回该值。
如果我们的值来自排除值,那么从 do --while 循环中,我们将再次调用 getRandomInt 来生成新值。