Similarly to generating a random float number within the specific range, you can write a function to get a random integer with a range.
function getRandomIntegerInRange(min, max) {
return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min)) + min;
}
The function getRandomIntegerInRange
returns a random number between min
(inclusive) and max
(exclusive).
If you want both min
and max
to appear as possible random return value, you should modify the function a bit
by adding in a +1
.
function getRandomIntegerInRangeIncludingMax(min, max) {
return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1) + min;
}
Now the function getRandomIntegerInRangeIncludingMax
will return the random integer in a specific range and the max
value will sometimes appear as a return result.