Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
Shuffle Array and Display with Button With No Repeats

Say I had the following array: [x, y, z]

If I wanted to shuffle that array and display each element one by one (without repeating) on each button click, how would I write that function with Javascript to populate the paragraph? Also, would you recommend writing the code inline or on a separate sheet and then imbedding it? Thank you in advance.

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Title </title>
</head>

<body>
    <script src="javascript.js"></script>
    <div> 
        <p></p>
    </div>
    <div>
    <button onclick="displayElement()">Start</button>
    </div>
    
</body>

</html>
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need a shuffling function (I got one) and some structure around it for the button click that will reveal the shuffle.

var arr = ['x', 'y', 'z']
var button = document.querySelector(".my-button");
var reset = document.querySelector(".my-reset");
var shuffled = shuffle(arr)
var index = 0;

button.addEventListener('click', function() {
  if (index < shuffled.length) {
    console.log(shuffled[index]);
    index++
  }
})

reset.addEventListener('click', function() {
  shuffled = shuffle(arr)
  index = 0;
})



function shuffle(str_or_arr) {
  var a = typeof str_or_arr == 'string' ? str_or_arr.split('') : str_or_arr
  var n = a.length;
  for (var i = n - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }
  return typeof str_or_arr == 'string' ? a.join('') : a;
}
<button class="my-button">next</button>
<button class="my-reset">reset</button>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda