Méthode Math.random
La méthode Math.random retourne un nombre
aléatoire décimal entre 0 et 1.
Syntaxe
Math.random();
Utilisation
Pour obtenir un nombre aléatoire dans un intervalle
spécifique (décimal ou entier), il faut utiliser
des techniques particulières.
L'obtention d'un nombre décimal aléatoire entre
min et max se fait comme suit :
function getRandomArbitary(min, max) {
return Math.random() * (max - min) + min;
}
Et maintenant, obtenons un nombre entier aléatoire entre min
et max :
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Exemple
Affichons un nombre aléatoire entre 0
et 1 :
console.log(Math.random());
Résultat de l'exécution du code :
0.5416665468657356
Exemple
Affichons un nombre entier aléatoire entre
10 et 100 :
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(10, 100));
Résultat de l'exécution du code :
12