select random value NOT in array

后端 未结 5 940
渐次进展
渐次进展 2021-01-20 07:56

How would I select a random value (0 to 30) that is not in this array?

var list = new Array(1,3,4,7,8,9);
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 08:07

    A little recursive function:

    getNum() {
      let randomNum = Math.floor(Math.random() * (30 - 1)) + 1
      if (list.includes(randomNum)) {
        return getNum()
      }
       return randomNum
    }
    

    Might be a little faster, since it first tries to return a random number, and then checks if it's in the array.

提交回复
热议问题