Friday, February 7, 2025

JavaScript Primers#26

Use these to jump around or read it all


The Concept

The Script

The Script’s Effect

Deconstructing the Script

What You’ve Learned

Your Assignment



The Concept

This example is the final new topic in our tutorial. It introduces arrays. You have already learned about variables. Each variable contains one value at a time, but sometimes you need an array or a variable that contains many values.

In this example, the user is asked to guess the program’s favorite state from a list of states. The prompt statement is repeated until the user guesses the state. Each time the button to start the guessing game is pressed, a new random state is selected.



The Script

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
     states=new Array()
     states[0]="CT"
     states[1]="PA"
     states[2]="NJ"
     states[3]="NY"
     states[4]="RI"
     num=0
function pickstate()
    {
       now=new Date()
       num=(now.getSeconds())%5
     }
function whichstate()
 {
 pickstate()
 guess="****"
 while (states[num] != guess.toUpperCase())

 {guess=prompt("What's my favorite state: 
          CT, PA, NJ, NY, or RI?")

  if (guess.toUpperCase() == states[num])
  {alert("That's my favorite state!")}
  else
  {alert("No, Try again")}}
  }
 </SCRIPT>    
</HEAD>
<BODY>
<FORM>

 <INPUT TYPE="button" VALUE="Guess" 
     onClick="whichstate()">

</FORM>
</BODY>
</HTML>



The Script’s Effect




Deconstructing the Script

 <SCRIPT type="text/javascript">
     states=new Array()
     states[0]="CT"
     states[1]="PA"
     states[2]="NJ"
     states[3]="NY"
     states[4]="RI"
     num=0

  • states=new Array() declares “states” as an array object. With the (parentheses) blank, the array can be any length. You can also specify the array’s length, e.g. states=new Array(5).

  • Remember that an array can have multiple values. We can picture this array as follows:
    states

    states[0] states[1] states[2] states[3] states[4]
    CT PA NJ NY RI
  • Notice we are preloading the variable num, which has one value, 0, and the array states, which has 5 values.
  • Now the pickstate() function:

    function pickstate()
        {
           now=new Date()
           num=(now.getSeconds())%5
         }
    

  • The function picstate() picks a random number between 0 and 4 that becomes the index of states. Remember, zero through four is FIVE numbers. We assigned a state the number zero, e.g., if num is 2, the favorite state is states[2],
    or NJ.
  • Now the whichstate() and pickstate() functions:

    function whichstate()
    {
     pickstate()
     guess="****"
     while (states[num] != guess.toUpperCase())
    
     {guess=prompt("What's my favorite state:
        CT, PA, NJ, NY, or RI?")
    
     if (guess.toUpperCase() == states[num])
      {alert("That's my favorite state!")}
     else
      {alert("No, Try again")}}
     }
    

    The “guess=prompt” statement above should all be on one line.

  • Here’s something new! Notice the first statement in this function calls another function, pickstate(). Thus whenever the user clicks the “Guess my favorite State” button, a new random state is selected.
  • Notice while (states[num] != guess.toUpperCase()). The method, or action, toUpperCase() is used to change whatever the user typed in to uppercase.
  • The program repeats the While loop until the user guesses the correct state. The While loop section should be pretty familiar by now.
  • Notice the If and Else statements. This game only has two outcomes. You’re either right or you’re wrong.
  • Now the button that starts it all:

    <FORM>
    
     <INPUT TYPE="button" VALUE="Guess!" 
        onClick="whichstate()">
    
    </FORM>

    That format should also look pretty familiar by now.

Here’s a little more on arrays:

  • There are several built-in arrays in JavaScript. Forms can be kept in arrays. You can reference a form as document.myform or as document.forms[0], if this is the first form. Notice arrays always start at 0. The second would be document.forms[1]. The third would be document.forms[2]. And so on…
  • Images can also be kept in a built-in array. You can reference a pic1.gif as document.pic1.src or as document.images[0].src. Just continue following the pattern, adding a number inside the square brackets.

  • Got the general idea of arrays?



What You Have Learned




Your Assignment

Write a JavaScript program that contains a button with the label “Click to go to a Random Site.” When the user clicks this, it will run a function that will set num to a random number and pick a site from an array with the JavaScript command top.location.href = urls[num]. top is a property of the window object and refers to the top-most browser window. location.href, another object and property, contains the URL address.

Here’s a possible answer to this assignment
(this will open a new window)



The Concept

The Script

The Script’s Effect

Deconstructing the Script

What You’ve Learned

Your Assignment


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured