Random Int JS
Random from 0 to <MAX
// From 0 (inclusive) to Max (not including)
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var res = getRandomInt(7);
console.log(res); // Result: 0, 1, 2, 3, 4, 5, 6.
Random from MIN to <MAX
// From Min (inclusive) to Max (not including)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
var res = getRandomInt(3,7);
console.log(res); // Result: 3, 4, 5, 6.
Random from MIN to <=MAX
// From Min (inclusive) to Max (including)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}
var res = getRandomInt(3,7);
console.log(res); // Result: 3, 4, 5, 6, 7.