<!-- SophiaKnows -->

JAVASCRIPT BASICS
Rev 4: December 2004

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

 

2. What is a JavaScript Array?

A JavaScript Array is a variable data object that stores temporary values assigned by the programmer in the form of an ordered list: (value1, value2...)

Like the (unitary) variables we have already seen Arrays can store: (1) quoted string literals, (2) integers and decimal number values; (3) variable names; and (4) even the keynames of other array objects.

An array is explicitly created by assigning the reserved word new and the contructor Array() to a keyname (or array label) selected by the programmer when first declared:

var array-label=new Array();

As with unitary variable labels, the array name can consist of letter and number characters (a-z A-Z 0-9). The name can include the underscore character but not spaces, punctuation or special characters:

var messageList = new Array();
var message_list = new Array();
var messages_2 = new Array();

2.1 Array Types:

There are two general types of JavaScript arrays: Indexed Arrays; and Associative Arrays.

Element values of an indexed array are stored and retrieved using an integer representing the element's order in the list (0-n).

var eg1=new Array();
eg1[0]="Example 1";
eg1[0]="Example 2";

Element values of an associative array are stored and retrieved using unique, associative string key names.

var eg2=new Array();
eg2['ex1']="Example 1";
eg2['ex2']="Example 2";

2.2 Indexed Arrays: Indexed arrays can be created and populated in one of two ways:

First, at the time the array is declared the programmer can insert a list of initial values as a comma delineated list (value1, value2 ...) within the parenthesis of the reserved word Array():

var array-label=new Array(value_1,[value_2] ... );

The following example creates an array named "messageList" with two stored values ("Hello World" and "Goodbye World"). Note that string literals need to be enclosed in either single ('') or double quotes (""):

var messageList=new Array("Hello World","Goodbye World");

Note also that the implied order of each element in the list is represented by a number between 0 and a number n where n is an integer less than the total number of members in the list

Second, values can be assigned to the Array() by list index (0, 1, 2 ...). Note that the array still needs to be created in another statement proceeding the assignment(s):

var array-label=new Array();
array-label.[item-index]=value;

var messageList=new Array();
messageList[0]="Hello World";
messageList[1]="Goodbye World";

Developers can add a new member to the list

messageList[2]="Aloha World";

Reset the value of an existing member:

messageList[1]="Adios World";

Start at a number other than zero:

messageList[1]="Hello World";
messageList[2]="Goodbye World";

Even skip values:

messageList[1]="Hello World";
messageList[15]="Goodbye World";

Regardless of the initial assignment method used, values are recalled from the Array() using the item's list index:

Listing   2.1
var messageList=new Array("Hello World","Goodbye World");

document.write(messageList[0]);
document.write(messageList[1]);
Hello World
Goodbye World

2.2.1 Indexed Array Properties

2.2.1.1 Length

Indexed arrays have a single property length which is a number indicating the number of members in the list.

array-label.length;
var students=new Array("Tom","Mary","Anne","Ahmed");
students.length;

Which in this case returns 4

Listing   2.2
var students=new Array("Tom","Mary","Anne","Ahmed");

document.write("<p>There are "); 
document.write(student.length); 
document.write(" students</p>"); 

There are 4 students

The real value of length however is that it tells you programatically how many members there are in the list, and the index of last member is always one less than the total number of entries (length-1):

var last_student = students[students.length-1];

This may not appear immediately useful, however its utility should become more apparent in the next section (Part 4: Control Structures)

2.2.2 Indexed Array Methods

2.2.2.1 sort()

The Array() sort() method sorts the array elements in descending ASCII order (A-Z)

array-label = array-label.sort();

The sorted array can be assigned to itself (permanently replacing the original order). The sorted array can also be assigned as a copy to another variable (preserving the original order)

students=students.sort();

var a_z_students=students.sort();

2.2.2.2 reverse()

The reverse() method reverses the existing order of the array elements.

array-label = array-label.reverse();

If the list has been sorted using the sort() method, this will result in a reverse alphabetical order:

students=students.sort();
students=students.reverse();

students=students.sort().reverse();

2.1.2 Associative Arrays:

Associative arrays must also be initially declared using the Array() constructor:

var array-label=new Array();

Instead of an ordered index, however, values are stored and retrieved from the array using a unique key which can be, among other things, a text-string, integer, decimal, variable reference or the results of an operation.

array-label[item-key]=value;

2.1.2.1 Simple Associative Arrays:

Here is a simple associative array grades using student first names as item keys:

var grades=new Array();

grades['Ahmed']="A+";
grades['Mary']="A";
grades['Tom']="B";
grades['Anne']="C";

Here is an indexed array of student names in reverse alphabetical order:

var students=new Array("Tom","Mary","Anne","Ahmed");

And here is how the ordered list of student names could be used to generate the associative keys and retrieve values from the associative array grades:

Listing   2.3
var students=new Array("Tom","Mary","Anne","Ahmed");

var grades=new Array();

grades['Ahmed']="A+";
grades['Mary']="A";
grades['Tom']="B";
grades['Anne']="C";

document.write("<table>");
document.write("<tr><td>"+students[0]+"<td>"+grades[students[0]]);
document.write("<tr><td>"+students[1]+"<td>"+grades[students[1]]);
document.write("<tr><td>"+students[2]+"<td>"+grades[students[2]]);
document.write("<tr><td>"+students[3]+"<td>"+grades[students[3]]);
document.write("</table>"); 
Tom:B
Mary:A
Anne:C
Ahmed:A+

Note that, although they have a fixed incidental order, associative arrays have no intrinsic internal index. Despite the incidental sequence in which the assignment was made the in example above, Tom's grade does not have an index of 2, and the value grades[2] will return undefined.

2.1.2.1 Complex Associative Arrays:

An associative array can also be declared using something like the following syntax to assign text-key and text-value pairs to the array (note the syntax does not use the Array() constructor):

var array-label={ val_1 : "val 1", val_2 : "val 2" };

Or to use a more concrete example, here is a one off array named employee:

var employee={ f_name: "Carl", l_name: "Wilson", phone: "548" };

The variable statement employee['phone'] now returns 548.

Not especially complex and in fact briefer than the method shown in the simple example above. However, this method only really becomes useful when we have more employees than just "Carl". What we really want is a list of lists.

So we will create a parent array named employees using last names as a text-key to hold several associative arrays in turn storing more detailed employee information

Listing   2.4
var employees = new Array();

employees['Gould']={ f_name : "Glenn", l_name : "Gould", phone : "547" };
employees['Marx']={ f_name : "Allan", l_name : "Marx", phone : "542" };
employees['Peters']={ f_name : "Mary", l_name : "Peters", phone : "544" };
employees['Wilson']={ f_name : "Carl", l_name : "Wilson", phone : "548" };

document.write("<p>");
document.write(employees['Peters']['f_name'] + " ");
document.write(employees['Peters']['l_name'] + " x ");
document.write(employees['Peters']['phone']);
document.write("</p>");

That was a lot of work just to print three values, but the first listing (3.1) in next section Part 3: Control Structures shows how some automation can be added to make this a little more productive.

Part 2 of 9 | Next Part 3: Control Structures >

 

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

< CODEBASE | TOP^ | MAINPAGE >

Text & Design By Tony Pisarra
© SophiaKnows 1998-2004