Show result of a random array!

Asked

Viewed 45 times

-3

Good evening! I’m new to Javascript. I did a study of the word memorization type where I pick a certain number of words within an Array. The words are random and shown one by one. But I would like to implement a button to show all the words that were chosen in a list, as an answer to check later. Can someone give me a way? Thank you.

o index:

 <div id="container">
    <h1>Random</h1>

    <div id="random"></div>

    <select  id="palavras"> 
        <option value="10"  selected>10 palavras</option>
        <option value="20" >20 palavras</option>
        <option value="30">30 palavras</option>
    </select>


    <button id="iniciar" >Iniciar</button>
    <button id="resposta" style=" display: none;">Resposta</button>


    <select  id="tempo"> 
        <option value="1000"  selected>1 segundo</option>
        <option value="2000" >2 segundos</option>
        <option value="5000">5 segundos</option>
    </select>

   <div id="lista" style=" display: none; margin-top: 50px;"> 
 
</div>


O script.js

 let random = document.getElementById('random');
 let resposta = document.getElementById('resposta');
 let tempo = document.getElementById('tempo');
 let palavras = document.getElementById('palavras');
 let inicar= document.getElementById('iniciar');



function randomWords(min, max){
   let step1 = max - min +1;
   let step2 = Math.random() * step1;
   let result = Math.floor(step2) + min;
   return result;
}

let words =  [
 
  'Barriga',
  'Bicicleta',
  'Formiga',
  'Garrafa',
  'Teclado',
  'Mouse',
  'Caneca',
  'Cerveja',
  'Barata',
  'Cigarro',
  'Café',
  'Copo',
  'Poste',
  'Bola',
  'Balão',
  'Igreja',
  'Padre',
  'Carro',
  'Caminhão',
  'Monitor',
 
];



function verificaDez(){
  if(words.length == 20){
    random.innerText = "Clique em resposta par ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex];   
 words.splice(randomIndex,1);      
 random.innerText = randomWord;  

}


function verificaVinte(){
  if(words.length == 10){
    random.innerText = "Clique no botão resposta para ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex];   
 words.splice(randomIndex,1);      
 random.innerText = randomWord;  

}

function verificaTrinta(){
  if(words.length == 0){
    random.innerText = "Clique em resposta par ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex];   
 words.splice(randomIndex,1);      
 random.innerText = randomWord;  

}

iniciar.addEventListener("click", function( ) {
  if(palavras.value == 10){
    setInterval(verificaDez, tempo.value);
  }else if ( palavras.value == 20){
    setInterval(verificaVinte, tempo.value);
  }else if( palavras.value == 30){
    setInterval(verificaTrinta, tempo.value);
  } 
}
);


resposta.addEventListener("click", function( ) { 
  
}
);

https://jsfiddle.net/wnobre/epzLm05r/ " Example of how it turned out"

  • @Rafaeltavares I’ve actually managed to generate the random words! What I didn’t get was after showing the random words , recover and show all at once in a list. I don’t know if I could understand, rs

  • Do you say in the answer? Your event reply click the function is empty...

  • @Magichat Yes! It’s empty, because I don’t know how to return those words that were shown randomly. That’s exactly my question.

  • Um, I get it... and you didn’t even try anything?

  • @Magichat I tried everything I knew, rs! But, I am beginner and nothing worked.

  • So the ideal is to put the code you tried...

Show 2 more comments

1 answer

2

Follow the following steps:

  1. Create a variable within the global scope containing an empty array.
const displayedWords = [];
  1. Substitute words.splice(randomIndex,1)) within its "check" functions by the following code, which will add each drawn word to the previously created array:
displayedWords.push(words.splice(randomIndex,1)[0]);
  1. Fill in the function called by clicking "Answer" with this code, which will add a list containing the words drawn to your HTML:
  const list = document.createElement('ul');
  list.style.paddingLeft = '0';
  displayedWords.forEach((word) => {
    list.insertAdjacentHTML('beforeend', `<li>${word}</li>`);
  });
  document.querySelector('#container').insertBefore(list, random);
  displayedWords.length = 0;

The complete code would look like this:

let random = document.getElementById('random');
 let resposta = document.getElementById('resposta');
 let tempo = document.getElementById('tempo');
 let palavras = document.getElementById('palavras');
 let lista = document.getElementById('lista');
 let inicar= document.getElementById('iniciar');



function randomWords(min, max){
   let step1 = max - min +1;
   let step2 = Math.random() * step1;
   let result = Math.floor(step2) + min;
   return result;
}

let words =  [
 
  'Barriga',
  'Bicicleta',
  'Formiga',
  'Garrafa',
  'Teclado',
  'Mouse',
  'Caneca',
  'Cerveja',
  'Barata',
  'Cigarro',
  'Café',
  'Copo',
  'Poste',
  'Bola',
  'Balão',
  'Igreja',
  'Padre',
  'Carro',
  'Caminhão',
  'Monitor',
  '1',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9',
  '10',
 

];

const displayedWords = [];


function verificaDez(){
  if(words.length == 20){
    random.innerText = "Clique em resposta par ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex];   
 displayedWords.push(words.splice(randomIndex,1)[0]);      
 random.innerText = randomWord;  

}


function verificaVinte(){
  if(words.length == 10){
    random.innerText = "Clique no botão resposta para ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex];   
 displayedWords.push(words.splice(randomIndex,1)[0]);         
 random.innerText = randomWord;  

}

function verificaTrinta(){
  if(words.length == 0){
    random.innerText = "Clique em resposta par ver o resultado"; 
    document.getElementById('resposta').style.display = "block";   
     return;       
 }    
 let randomIndex = randomWords (0,words.length-1) ;
 let randomWord = words[randomIndex]; 
 displayedWords.push(words.splice(randomIndex,1)[0]);       
 random.innerText = randomWord;  

}

iniciar.addEventListener("click", function( ) {
  if(palavras.value == 10){
    setInterval(verificaDez, tempo.value);
  }else if ( palavras.value == 20){
    setInterval(verificaVinte, tempo.value);
  }else if( palavras.value == 30){
    setInterval(verificaTrinta, tempo.value);
  } 
}
);


resposta.addEventListener("click", function( ) { 
  const list = document.createElement('ul');
  list.style.paddingLeft = '0';
  displayedWords.forEach((word) => {
    list.insertAdjacentHTML('beforeend', `<li>${word}</li>`);
    });
  document.querySelector('#container').insertBefore(list, random);
  displayedWords.length = 0;
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random</title>
<style>

    body{
        margin: 0, auto;
    }
    #random {
      margin-bottom: 30px;
    }
  
    #tempo {
        margin-top: 20px;      
    }
    input{
        width: 20px;
    }
    ul{
        list-style: none;
    }

    
</style>

</head>
<body>
    <center>
   <div id="container">
    <h1>Random</h1>

    <div id="random"></div>

    <select  id="palavras"> 
        <option value="10"  selected>10 palavras</option>
        <option value="20" >20 palavras</option>
        <option value="30">30 palavras</option>
    </select>


    <button id="iniciar" >Iniciar</button>
    <button id="resposta" style=" display: none;">Resposta</button>


    <select  id="tempo"> 
        <option value="1000"  selected>1 segundo</option>
        <option value="2000" >2 segundos</option>
        <option value="5000">5 segundos</option>
    </select>

   <div id="lista" style=" display: none; margin-top: 50px;"> 
 
</div>
  
    
</div>
</center> 

  <script src="script.js"></script>   
</body>
</html>

Tip: join your "check" functions into one, passing variable data per parameter.

  • Man! Exactly what I needed. Thanks. About your tip, I’ll give a study. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.