How do I randomly generate a name by clicking on the button?

Asked

Viewed 57 times

-1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@900&display=swap" rel="stylesheet">
    <script src="./script/gerador.js"></script>
    <title>Lista da Semana</title>
</head>
<body>

    <h2>Lista da Semana</h2>



    <div class="container">
      
      
    <button class="but1" onclick="gerar_nomes()">Gerar Local</button>

    </div><!--container-->  

    
</body>
</html>



function gerar_nomes(){

    var nomes = [
        'Daniel', 
        'Gabriel', 
        'Thiago', 
        'Leozinho', 
        'Pedro', 
        'Fernando', 
        'Marco', 
        'Gleica', 
        'Yudi', 
        'Wesley', 
        'Renan'
    ];
    var gerador ='#';

}

alert(gerar_nomes);

2 answers

0

Each item of the array can be accessed via nomes[0], nomes[1], nomes[2] (...). So if you want to choose one of them, you can use nomes[um_numero_aleatorio].

The only thing you have to ensure is that the um_numero_aleatorio is within the limits of the array (in this case: nomes.lenght - 1).


window.document.querySelector("button").addEventListener("click", function(_) {
  const nomes = ["Daniel", "Gabriel", "Thiago", "Leozinho", "Pedro", "Fernando", "Marco", "Gleica", "Yudi", "Wesley", "Renan"];
  const index_maximo = nomes.length - 1;        // = 10
  const index_aleatorio = random(index_maximo); // = Numero de 0 até 10

  alert(nomes[index_aleatorio]);
})

function random(v) {
  var r = new Uint8Array(1); // PS: Suporta no máximo 256 items.
  window.crypto.getRandomValues(r);
  if (r[0] <= v) {
    return r[0];
  }
  return random(v); // PS: Pode causar loop infito se todos os numeros gerados forem maiores que v. É possível aumentar a probabilidade removendo os bits baseado no número máximo (ex. se o limite é 10 cabe em apenas 4bits, limitando de 0 até 16).
}
<button>Gerar</button>


The above example makes use of the crypto.getRandomValues, instead of math.Random.

-1


Oops, I did this example on reactJS as a demonstration, but you can get the same idea of how to solve your problem, with the Math you may be generating this random number by picking the index of each array and bringing its value. I hope it helps, any doubt just talk. Hugs

import React, { useState } from "react";

export default function App() {
  const [nome] = useState([
    "Daniel",
    "Gabriel",
    "Thiago",
    "Leozinho",
    "Pedro",
    "Fernando",
    "Marco",
    "Gleica",
    "Yudi",
    "Wesley",
    "Renan"
  ]);
  
  const [newName, setNewName] = useState("");

  function gerar_nomes() {
    let countNome = nome.length;

    let nomeRandom = randomName(countNome);

    setNewName(nome[nomeRandom]);
  }

  function randomName(countName) {
    return Math.floor(Math.random() * countName);
  }

  return (
    <div className="App">
      <h1>{newName}</h1>
      <button onClick={() => gerar_nomes()}>
        Gerar Nome
      </button>
    </div>
  );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.