0

I'm trying to write some code so that when the user clicks a button, the page writes the numbers 1 through 125, while modifying some in between My first question is how do I write the conde so that the function writes these numbers. Here's the code I have so far.

<script>
        function randomNumber() {
        var num = Math.floor(Math.random() * 125);
        for (var i = 0; i < 125; i++) {
        document.write(num);
        }
    </script>

My second question is how do I modify each a few of the numbers to read, for example, ten instead of 10. I assume that this will use a nested for loop, unless I'm wrong. Any help would be great! Thank you.

1 Answers1

0

your code is on the right track

<script>
   function randomNumber() {
      for (var i = 0; i < 125; i++) {
         var num = Math.floor(Math.random() * 125);
         console.log(num);
         //document.write(num); - bad!
      }
   }

   document.getElementById('yourElement').onclick = randomNumber;  
</script>

You didn't close off your function, unless it was a mis-copy. Also, your variable num needs to be within the for loop so it can call a random number each tick, unless you want one random number written 125 times, then keep num outside randomNumber().

Secondly, don't use document.write, it is bad practice. Utilize document.getElementById('yourElement').innerHTML = num.

Lastly, if you want to resolve the number based upon it's english counterpart, you will need an object with numbers 1 - 125, and their respective word set as the value of each number...

var numbers = {
   1: "one",
   2: "two"
   // etc....
}

In the loop you will need something along the lines of a switch or if/else if chain that has a condition for each number and utilizes your i increment as an index number[i] to print out the proper text.

Seth
  • 10,198
  • 10
  • 45
  • 68