需要修改代码,以便排除数组中存在的所有值

时间:2017-12-29 21:06:27

标签: javascript arrays

在下面的代码中,函数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;
}

我尝试使用indexOfincludes,但没有运气。

谢谢!

1 个答案:

答案 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