Overview
In this lesson we'll be working with multiple arrays. Here's an example of the page we'll be making. It produces a silly title by randomly selecting an adjective and two nonsense words put together for a noun.
Each time the page is loaded, a new silly title appears. This is a good way to generate random insults, too. All you need to do is to make three arrays and load them with the strings you want to use. Then, generate three random numbers to make selections from these arrays. Finally, display the selected strings.
Here's the basic procedure you'll use when dealing with array(s):
1) Make the array(s) and enter the array's objects
2) Make a selection from the array(s). This can involve IF comparisons, loops, and "Math" methods. We've used "Math.random()" and FOR loops.
3) Assign the selection(s) to a variable(s) that will be used in displaying the data
4) Code the display that will present the selected data on the page.
As much as you can do with JavaScript arrays, you'll be following the four steps above each time you use them.
I always like starting array projects at the last step -- making the display. This gives me a solid idea of the number of arrays and types of objects I'll be needing. In our current example, coding the display first gave me the idea of splitting the noun up into two strings and using "document.write()" to splice them together.
The code I used to display the selected strings uses "document.write()" in the page's <body>
<body>
<script language="JavaScript">
document.write("<h1 align=\"center\">" + adjective + "<\/h1>");
document.write("<h1 align=\"center\">" + first + second + "<\/h1>");
</script>
...
</body>
Nothing new here, but notice the use of the escape character (backslash,\) to nest quotes. Also note it's use before the forward slash (/). In some cases, the forward slash may cause mathematical division if the escape character isn't used. That's not a problem here, but it's a good habit to use the escape character before forward slashes in strings like HTML tags.
You'll also notice that I used two "document.write()s". You could put everything into one, but breaking things up makes the code easier to read and debug.
By making the display first, I can edit it and get the final result perfect before I've coded the full JavaScript program. This prevents me from having to rewrite a whole program if I want to change the display later. That's the big reason I start coding with the display first and the actual program second.
When coding the display first, you'll have to assign temporary values to the variables or you'll get errors. Use simple "var" assignments to do this:
<body>
<script language="JavaScript">
var adjective = "pompous";
var first = "Flugle";
var second = "snort";
document.write("<h1 align=\"center\">" + adjective + "<\/h1>");
document.write("<h1 align=\"center\">" + first + second + "<\/h1>");
</script>
...
</body>
These variable assignments are temporary and only used to test and debug the display code. They are deleted after the display code is tweaked. Using temporary data in this manner is called using "stub" data or "stubbing".
The Arrays
After coding the display, move on to making the arrays you'll need. We'll need three arrays to make our example. One array each for the vars "adjective", "first", and "second". Here's a sample from the "adjective" array that I'll name "adjList". Note that this code is put between <script> tags in the page's <head>. You could also use an external .js file.
adjList = new Array();
adjList[0] = "Snotty";
adjList[1] = "Flatulent";
...
adjList[9] = "Cryptic";
The other two arrays are similarly coded assigning appropriate strings as objects to the arrays. It's important to note that each array can have any number of objects. They don't have to be of equal length.
In fact, we'll be coding our random selection using "array_name.length" so we can easily add or remove objects from any of the arrays without having to change any of the rest of the code.
The Random Numbers
With our arrays made and objects assigned, we can start coding our selection process. In our case we want to make a random selection from each array. This will require three random numbers. I'll call the first random number "rand1" and create it using the Date() object's seconds for a seed number.
now = new Date();
seed = now.getSeconds();
var rand1 = Math.round(Math.random(seed) * adjList.length);
There's a little bit to talk about here. We made a Date() object and extracted the seconds value. The seconds are assigned an object name of "seed". Next we set a variable called "rand1" to equal a rounded and fully processed random number.
Pay close attention to what's going on in "rand1's" assignment. We've taken all of the steps of the previous lesson and put them on one line.
Make sure you understand each step of the random number generation process. First we generated a random number with a seed number. Next, we multiplied this by the number of objects in the "adjList" array using "adjList.length". This gives us our range.
Finally, we round this number to remove the digits to the right of the decimal point. It is crucial that you nest these processes correctly. Nesting mathematical processes works like other nesting.
Keep in mind that the last process you want to perform is the "parent" process containing the other processes. That's how math nesting goes: The first processes are in the middle and subsequent process "contain" the previous processes. Keep up with those parentheses.
Now we need to add the error control for the "rounding problems" we encountered in our previous lesson.
now = new Date();
seed = now.getSeconds();
var rand1 = Math.round(Math.random(seed) * adjList.length);
if (rand1 == adjList.length){rand1 = 0}
We can use the same seed number to make the other two random numbers we need. Remember that we need to use different variable names for the different random numbers we want to generate. We must also associate each random number with the length of the array it is to select from.
Here's the code for the other two random numbers.
//second random number
var rand2 = Math.round(Math.random(seed) * firstList.length);
if (rand2 == firstList.length){rand2 = 0}
//third random number
var rand3 = Math.round(Math.random(seed) * secondList.length);
if (rand3 == secondList.length){rand3 = 0}
You should be able to understand the above. We're just making three random numbers instead of a single one. If you're confused about what's going on, review the previous lesson on how "Math.random()" works.
The Final Assignment
With our arrays made and a selection process coded, we can assign values to our display's variables:
var adjective = adjList[rand1];
var first = firstList[rand2];
var second = secondList[rand3];
Note that we had to use the "var" statement because we haven't declared these variables previously. Yes, we used them in creating the display code, but this will be their first occurrence when the program is run. Note: Don't forget to delete any "stub" values you may have assigned when developing the display.
Summary & Exercises
All array work involves four steps. I like to begin a project with the last step -- coding the display -- and then code steps 1-2-3
Step 1 -- Make the arrays and assign the array's objects. You can use as many arrays as you'd like in any given program.
Step 2 -- Design a selection process. This is a loop, math process, or IF condition that will select item(s) from your array(s).
Step 3 -- Assign variables to contain the selections made. These variables will generally be used in the final display of the data.
Step 4 -- Display your data. This is what it's all about. The final result of your program.
Make a random insult generator with two or more arrays. One array can contain adjectives and another nouns, like in our example. Play around with this until you get good at both making multiple arrays and using random numbers.
Make a multiple random slideshow where four different image areas display a random image every two seconds. This project is much easier if you begin by coding your display first. Hint: In this case, you can use one array of image file paths and multiple random numbers to make multiple selections from this single array. You'll need a separate random number for each image rollover area.
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|