Skip to content
Advertisement

JavaScript generate random number except some values

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

function generateRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var test = generateRandom(1, 20)

Answer

it should be or instead of and

function generateRandom(min, max) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return (num === 8 || num === 15) ? generateRandom(min, max) : num;
}

var test = generateRandom(1, 20)
Advertisement