Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

82
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda