Méthode Math.random

La méthode Math.random retourne un nombre aléatoire décimal entre 0 et 1.

Syntaxe

javascriptMath.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 :

javascriptfunction getRandomArbitary(min, max) {
  return Math.random() * (max - min) + min;
}

Et maintenant, obtenons un nombre entier aléatoire entre min et max :

javascriptfunction getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Exemple

Affichons un nombre aléatoire entre 0 et 1 :

javascriptconsole.log(Math.random());

Résultat de l'exécution du code :

javascript0.5416665468657356

Exemple

Affichons un nombre entier aléatoire entre 10 et 100 :

javascriptfunction 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 :

javascript12