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

88
Visualizações
Random array element creation into Dom only once JavaScript

I've got a problem to insert a random array element into the DOM. I want it to only do it once for each array element but the code keeps fetching the element infinitely.

I'm doing a card game and want the code to understand that I'm picking a card from the deck, so it should delete it from the array. but it keeps on going and repeat the same cards over and over when I click the button. The button should draw randomly a card only once.

Here is the code:

<!DOCTYPE html>

<html>
    <head>

    <title>TEST</title>

    <style>
    .testDivExe{
        border: 0.1em dashed black;
        
        width: 100%;

        background-color: rgb(192,192,192,0.6);
    }
    
    body{
        border: 0.1em dotted black;
        
        font-family: impact;
        font-size: 2em;
        background-color: rgb(192,192,192,0.4);
    }
    </style>
    </head>


    <header>
        <h1>ZONE</h1>
    </header>


    <body>
        <div class="testDivExe" id="testDivExeId">
            <button id="testClickId">click</button>
        <div>

    <footer>
    </footer>

    <script>
    //TEST1
    document.getElementById("testClickId").onclick = function testFunc1(){
        // RAND AND ARR
        var array1 = ["Hello", "There", "Some", "Things", "Never", "Change",];
    
    
        
        var deal = function(){
            var index = Math.floor(Math.random() * array1.length);
            var card = array1[index];
            array1.splice(index, 1);
            return card;        
        };

        // PER&CRE
        var object = document.createElement('p');
        object.innerHTML = deal(array1);

        //REND
        document.getElementById("testDivExeId").appendChild(object);
        
        return false;
    };

    </script>
    </body>
</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

array1 is created every time you click the button. You must store array1 in such a way that it retains its current value. You can declare array1 in the global scope or store the array in the browser memory. You should actually remove the card from the array (I recommend you use filter instead of splice). Finally make sure to create a new <p> only when at least one card exist.

<script>
    //TEST1

    // RAND AND ARR
    var array1 = ["Hello", "There", "Some", "Things", "Never", "Change",];

    document.getElementById("testClickId").onclick = function testFunc1() {
        if (array1.length === 0) // Check if exists any card.
            return;
        var deal = function () {
            var index = Math.floor(Math.random() * array1.length);
            var card = array1[index];
            array1 = array1.filter(c => c !== card); // Remove the card
            return card;
        };

        // PER&CRE
        var object = document.createElement('p');
        object.innerHTML = deal(array1);

        //REND
        document.getElementById("testDivExeId").appendChild(object);

        return false;
    };

</script>

about 4 years ago · Juan Pablo Isaza 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