Casuale JavaScript

Math.random()

Math.random() Restituisce un numero casuale tra 0 (incluso) e 1 (escluso):

Esempio

Math.random();				// Restituisce un numero casuale

Prova tu stesso

Math.random() Restituisce sempre un numero minore di 1.

Interi casuali JavaScript

Math.random() Con Math.floor() Utilizzati insieme per restituire un numero intero casuale.

Esempio

Math.floor(Math.random() * 10);		// Restituisce un numero tra 0 e 9

Prova tu stesso

Esempio

Math.floor(Math.random() * 11);		// Restituisce un numero tra 0 e 10

Prova tu stesso

Esempio

Math.floor(Math.random() * 100);	// Restituisce un numero tra 0 e 99

Prova tu stesso

Esempio

Math.floor(Math.random() * 101); // Restituisce un numero tra 0 e 100

Prova tu stesso

Esempio

Math.floor(Math.random() * 10) + 1; // Restituisce un numero tra 1 e 10

Prova tu stesso

Esempio

Math.floor(Math.random() * 100) + 1; // Restituisce un numero tra 1 e 100

Prova tu stesso

Una funzione casuale appropriata

Come puoi vedere dall'esempio sopra, creare una funzione casuale per generare tutti i numeri casuali è una buona idea.

Questa funzione JavaScript restituisce sempre un numero casuale tra mine maxtra

Esempio

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Prova tu stesso

Questa funzione JavaScript restituisce sempre un numero casuale tra min e maxtra

Esempio

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

Prova tu stesso