Skip to content
the poor coder

como gerar numeros aleatorios em javascript a partir de uma função

Poor Man
Published
Reading time
1 min read

Você pode gerar números aleatórios em JavaScript usando a função Math.random(). Esta função nos retorna um número real aleatório entre 0 (incluído) e 1 (excluído).

Text

        Math.random(); // retorna um número aleatório entre 0 e 1
    

Se você quiser gerar um número aleatório entre dois valores, você pode usar a seguinte fórmula:

Text

    Math.floor(Math.random() * (max - min + 1)) + min;

Aqui, min é o menor número e max é o maior número. Por exemplo, para gerar um número aleatório entre 1 e 10, você pode usar o seguinte código:

Text

    Math.floor(Math.random() * (10 - 1 + 1)) + 1;  // Retorna um número aleatório entre 1 e 10

Além disso, você também pode usar a função Math.random() para gerar outros tipos de valores, como strings e objetos. Por exemplo, para gerar um objeto aleatório de uma matriz, você pode usar o seguinte código:

Text

    var arr = [1,2,3,4];
    arr[Math.floor(Math.random() * arr.length)];  // retorna um objeto aleatório de arr

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC