JavaScript Primers#26

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478391/JavaScript-Primers26.htm (Back to article)

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

Here's a little more on 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

On To JavaScript Primer #27