JavaScript Random
- Vorige Pagina JS Wiskunde
- Volgende Pagina JS Logica
Math.random()
Math.random()
Retourne un nombre aléatoire entre 0 (inclus) et 1 (exclus):
Voorbeeld
Math.random(); // retourne un nombre aléatoire
Math.random()
Retourne toujours un nombre inférieur à 1.
Entiers aléatoires JavaScript
Math.random()
Avec Math.floor()
Utilisé ensemble pour retourner un entier aléatoire.
Voorbeeld
Math.floor(Math.random() * 10); // retourne un nombre entre 0 et 9
Voorbeeld
Math.floor(Math.random() * 11); // retourne un nombre entre 0 et 10
Voorbeeld
Math.floor(Math.random() * 100); // retourne un nombre entre 0 et 99
Voorbeeld
Math.floor(Math.random() * 101); // Retourneert een getal tussen 0 en 100
Voorbeeld
Math.floor(Math.random() * 10) + 1; // Retourneert een getal tussen 1 en 10
Voorbeeld
Math.floor(Math.random() * 100) + 1; // Retourneert een getal tussen 1 en 100
Een geschikte willekeurige functie
Zoals je van het bovenstaande voorbeeld kunt zien, is het een goed idee om een willekeurige functie te maken om alle willekeurige gehele getallen te genereren.
Deze JavaScript-functie retourneert altijd een willekeurig getal tussen min
(inclusief) en max
tussen (exclusief) en:
Voorbeeld
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
Deze JavaScript-functie retourneert altijd een willekeurig getal tussen min
en max
tussen (inclusief) en:
Voorbeeld
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
- Vorige Pagina JS Wiskunde
- Volgende Pagina JS Logica