在下面的代码中,函数randomBetween
生成一个随机数,函数randomBetweenAndExcluding
生成另一个与第一个不同的随机数:
$(document).ready(function () {
function randomBetween (min, max) {
var ceiling = max + 1;
return Math.floor(Math.random() * (ceiling - min)) + min;
}
function randomBetweenAndExcluding (min, max, excluding) {
var random;
do {
random = randomBetween(min, max);
} while(random === excluding);
return random;
}
问题:我正在尝试对其进行扩展,以便randomBetweenAndExcluding
排除数组中存在的任何数字。基本上编码以下内容的部分(需要更改的部分放在星号中):
$(document).ready(function () {
function randomBetween (min, max) {
var ceiling = max + 1;
return Math.floor(Math.random() * (ceiling - min)) + min;
}
function randomBetweenAndExcluding (min, max, ***[ARRAY WITH X # of ELEMENTS]******) {
var random;
do {
random = randomBetween(min, max);
} while(random === ***ANY ELEMENT WITHIN THE ARRAY****);
return random;
}
我尝试使用indexOf
和includes
,但没有运气。
谢谢!
答案 0 :(得分:1)
以下适用于我:
function randomBetween (min, max) {
var ceiling = max + 1;
return Math.floor(Math.random() * (ceiling - min)) + min;
}
function randomBetweenAndExcluding (min, max, array) {
var random;
do {
random = randomBetween(min, max);
} while(array.includes(random));
return random;
}
array = [1,2,5];
alert(randomBetweenAndExcluding(1,5,array))
你可以在这个JSFiddle上查看:SQL Fiddle