Home > Software engineering >  Javascript code to get several random elements from array not working
Javascript code to get several random elements from array not working

Time:04-20

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 >
        <p >Input an element</p>
        <div >
            <input  type="text" name="add-input" id="add-input">
            <button  onclick="addElement()">Add</button>
        </div>
    </div>
    <div >
        <div >
            <p >Choose the amount</p>
            <input type="text" name="amount-input" id="amount-input">
        </div>
        <button onclick="getElements()">Get elements</button>
    </div>


CodePudding user response:

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>

  • Related