How to present a sequence of results

Asked

Viewed 31 times

0

Hello, I created a random number generator with the following script:

<input type="number" name="minimum" id="minimum">

<input type="number" name="maximum" id="maximum">

<button class="aazul" onclick="result()">Generate</button>
<div class="card" id="resultz"></div>

<script>
    function result(){
  const min = document.getElementById("minimum").value;
  const max = document.getElementById("maximum").value;

  let sort = Math.floor(Math.random()*Math.floor(max))

  while(sort<min){

    sort = Math.floor(Math.random()*Math.floor(max));
  }

  document.getElementById("resultz").innerHTML=sort;
}
    </script>

But it generates a number and when you click the Generate button again it generates another number (as expected). I would like to save a list of 6 numbers generated as a history that would be possible or someone could indicate how to do this?

1 answer

-1

I would first re-evaluate the function to be more precise with the generated number, rather than staying in a loop until I can generate a number greater than the minimum:

function result() {
  const min = Number(document.getElementById("minimum").value);
  const max = Number(document.getElementById("maximum").value);
  const range = max - min + 1;
  const number = Math.floor(Math.random() * range + min);

  document.getElementById("resultz").innerHTML = number;
}

Now to save the last generated numbers just keep an array with these numbers. Use Array.push to add a value, and Array. to remove an amount of items from that array:

let results = [];

function result() {
  const min = Number(document.getElementById("minimum").value);
  const max = Number(document.getElementById("maximum").value);
  const range = max - min + 1;
  const number = Math.floor(Math.random() * range + min);

  results.push(number);
  if (result.length > 6) results = results.slice(1);

  document.getElementById("resultz").innerHTML = number;
}

This way the previous results were recorded in the variable Results.

  • In Amigo sorry for the insistence. How could I leave these 6 results on the page until I update it? I wanted to create a sequence with the last 6 numbers generated.

Browser other questions tagged

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