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

143
Visualizações
Javascript code to get several random elements from array not working

I've just started with JS, and I'm trying to get random elements from an array. The amount is decided by a user's input, and that part works, I think. The functions are called by onClick of buttons. Scouring the internet has given me the solution below as the best one, but I can't make the part of fetching elements work even in console.log.
What I actually see in console is an empty array [] with length:0

What's the matter with my code? This is the way to do it I keep seeing on forums and people say it works for them and it's basically the same code with changed words.

userArray = [];

    function addElement(){
        let element = document.getElementById("add-input").value;
        userArray.push(element); 
        document.getElementById("add-input").value = "";
    }


    function getElements(){
        let amount = document.getElementById("amount-input").value;
        newList = []; 
        for(i=0; i<amount.value; i++){
        randomElement = userArray[Math.floor(Math.random() * userArray.length)];
        newList.push(randomElement);
        }
        console.log(newList);
    }

   <div class="phase-add">
        <p class="label-p">Input an element</p>
        <div class="input-box">
            <input class="add-input" type="text" name="add-input" id="add-input">
            <button class="add-btn" onclick="addElement()">Add</button>
        </div>
    </div>
    <div class="phase-get">
        <div class="input-box">
            <p class="label-p">Choose the amount</p>
            <input type="text" name="amount-input" id="amount-input">
        </div>
        <button onclick="getElements()">Get elements</button>
    </div>


about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The Variable amount is already a string/number. You need not get the value of it again in the for loop. Changing to for(i=0; i<amount; i++){ in for loop will fix the issue.

userArray = [];

function addElement(){
    let element = document.getElementById("add-input").value;
    userArray.push(element); 
    document.getElementById("add-input").value = "";
}


function getElements(){
    let amount = document.getElementById("amount-input").value;
    console.log(amount)
    newList = []; 
    for(i=0; i<amount; i++){
      randomElement = userArray[Math.floor(Math.random() * userArray.length)];
      newList.push(randomElement);
    }
    console.log(newList);
}
<input id = "add-input" type = "text" ></input>
<button onclick = "addElement()">Add Element</button>
<input id = "amount-input" type = "number"></input>
<button onclick = "getElements()">Get Elements</button>

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