JavaScript Aléatoire
Math.aléatoire()
Math.random()
renvoie un nombre aléatoire entre 0 (inclus) et 1 (exclusif) :
Exemple
// Returns a random number:
Math.random();
Math.random()
renvoie toujours un nombre inférieur à 1.
Entiers aléatoires JavaScript
Math.random()
utilisé avec Math.floor()
peut être utilisé pour renvoyer des entiers aléatoires.
Les entiers JavaScript n'existent pas.
Nous parlons ici de nombres sans décimales.
Exemple
// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);
Exemple
// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);
Exemple
// Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);
Exemple
// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);
Exemple
// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
Exemple
// Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;
Une fonction aléatoire appropriée
Comme vous pouvez le voir dans les exemples ci-dessus, il peut être judicieux de créer une fonction aléatoire appropriée à utiliser à toutes les fins d'entiers aléatoires.
Cette fonction JavaScript renvoie toujours un nombre aléatoire entre min (inclus) et max (exclu) :
Exemple
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
Cette fonction JavaScript renvoie toujours un nombre aléatoire entre min et max (les deux inclus) :
Exemple
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}