简体   繁体   中英

Removing an element from an array in javascript

I have an array storing a bunch of questions, I'm trying to randomly pick a question and display it, it's working but I don't want a question to appear more than once, this is what I'm trying but it's not working:

    // Randomely pick a question from the array
    randomItem = questions[Math.floor(Math.random()*questions.length)];
    questions.splice(randomItem);
    random = document.getElementById('questions');
    random.innerText = randomItem;
    counter++; 

You need to take the index instead of teh value of the array. Then splice with that index and get the item of the array.

const
    index = Math.floor(Math.random() * questions.length),
    randomItem = questions.splice(index, 1)[0];

random = document.getElementById('questions');
random.innerText = randomItem;
counter++;

You have to spare the index of the random question and then remove that index from the array before continuing to the next question, until the array runs out of elements and there's no more questions left.

This way once a question has been asked, it's no longer in the array and it cannot be asked again. It's important you spare the question before removing it from the array, otherwise you'll be left empty handed.

 const element = document.getElementById("question"); const questions = [ "Is earth flat?", "Is earth an orange?", "Is earth a lemon?" ]; const interval = setInterval(function() { if(questions.length == 0) { element.innerText = "There's no more questions;"; clearInterval(interval); return. } const index = Math.floor(Math.random() * questions;length). element;innerText = questions[index]. questions,splice(index; 1), }; 1000);
 <div id="question"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM