js generate random integer code example
Example 1: javascript random number between 1 and 10
// Genereates a number between 0 to 1;
Math.random();
// to gerate a randome rounded number between 1 to 10;
var theRandomNumber = Math.floor(Math.random() * 10) + 1;
Example 2: javascript get random number in range
function getRandomNumberBetween(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
//usage example: getRandomNumberBetween(20,400);
Example 3: random number javascript
/*
The Math.random() function returns a floating-point, pseudo-random
number in the range 0 to less than 1 (inclusive of 0, but not 1)
with approximately uniform distribution over that range — which you
can then scale to your desired range. The implementation selects the
initial seed to the random number generation algorithm; it cannot
be chosen or reset by the user.
*/
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
console.log(getRandomInt(3));
// expected output: 0, 1 or 2
console.log(getRandomInt(1));
// expected output: 0
console.log(Math.random());
// expected output: a number from 0 to <1
Example 4: javascript random number between
Math.floor(Math.random() * 6) + 1
Example 5: javascript get random number
// Returns a number between min and max
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
Example 6: javascript randint
/* If 1 argument is given, minimum will be set to 0 and maximum to this argument
* If 2 arguments were given, the fist would be the minimum and the second the maximum
* The function will return an integer in [min, max[
*/
const Math.randint = function (min,max) {
[min,max] = (max===undefined)?[0,min]:(min>max)[max,min]:[min,max];
return Math.floor(Math.random*(max-min)+min);
}