JavaScript generate random number except some values

后端 未结 13 1752
野性不改
野性不改 2021-01-05 11:26

I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(mi         


        
13条回答
  •  情歌与酒
    2021-01-05 11:58

    I've read through all these answers and they differ a lot in philosophy, so I thought I might add my very own 2 bits, despite of this question having an answer, because I do think there is a better and more elegant way of approaching this problem.

    We can make a function that takes min, max and blacklist as parameters and outputs a random result without using recursion (and with close to 0 if statements):

    const blrand = function(min, max, blacklist) { if(!blacklist) blacklist = [] let rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; let retv = 0; while(blacklist.indexOf(retv = rand(min,max)) > -1) { } return retv; }

    usage: let randomNumber = blrand(0, 20, [8, 15]);

提交回复
热议问题