EMZETT.
Login

Math.random und Math.floor

Kurz: Math.random() liefert in JavaScript eine Zufallszahl von 0 (inklusive) bis 1 (exklusive). Math.floor(x) rundet auf die nächste ganze Zahl nach unten. Zusammen erzeugt man ganzzahlige Zufallswerte.

Genauer: Die Zufallszahl ist eine Dezimalzahl, zum Beispiel 0.7342. Um eine Zahl in einem Bereich zu bekommen, skaliert man sie mit der Bereichsgröße und rundet ab.

Im Detail

// ganze Zahl von 0 bis 5 (Würfel minus 1)
const w = Math.floor(Math.random() * 6);
// Würfel 1 bis 6
const wuerfel = Math.floor(Math.random() * 6) + 1;
// Bereich min..max (inklusive)
const zufall = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

Siehe auch: zufallswerte, mathematische-funktionen