Concepts in Computing
CS4 - Winter 2007
Instructor: Fabio Pellacini

Lecture 10: More JavaScript

Overview

• Other input types: check boxes, selections, and radio buttons
• Arrays

Arrays and Loops

Sometimes you need a collection of things (e.g., telephone directory). As we saw in pseudocode, an array allows us to store such a collection. An array is an ordered sequence; each member of the sequence has an index. JavaScript supports such arrays. The elements of an array are variables, so you can use them in the same ways. In CS, we usually number things starting from zero, so if there are 4 things in the array, we number them 0-3.

To create an empty array:

var v = new Array(); // Create a new empty array

Then we can put whatever we want in it:

v = "Hello";
v = 5;
v = 3.14;
v = document.helloForm;
v = v+v;

To create an array with a pre-determined set of entries:

var v = [ "Hello", 5, 3.14 ];

To find out how many things are in an array:

v.length

To loop through an array:

i = 0;
while (i < v.length) {
// do some stuff
i = i + 1;  // also i += 1;
}

This loops over everything in the array. We do this so often, that there is another way to write it:

for (i = 0; i < v.length; i += 1) {
// do some stuff
}

The first part, i=0 initializes a variable that will hold the current position in the array (done just before the while loop). The second part, i < v.length is a test, just like in the while loop. The third part, i += 1 updates the position (done at the end of the while loop body). These are equivalent; I don't care which you use, as long as you know what is going on in your own code! But you will see the for loop, so I wanted you to understand it.

Other input types

Check boxes

Example

To get the value of a check box, cross-reference by its name within the form, the same way as with texts. Then, rather than asking for its value, ask for whether or not it is checked -- a Boolean value (true or false).

if (document.form.checkbox.checked) {
// do some stuff
}

Selections

Examples

The various options of a selection make up an array. To find which member was selected, cross-reference by name and get its selectedIndex

index = document.form.option.selectedIndex;