Credits

Help with JavaScript

Thanks to Brenden Eich of Netscape for explaining to me how to create the original JavaScript Arrays back when the language was known as Livescript. You can find further documentation of JavaScript arrays in the Netscape documentation:

Please note that Javascript arrays have changed drastically between Netscape 3 and 4 (Communicator). If you are using communicator, you can still use the old syntax if you do NOT specify "language=Javascript 1.2" in your script tag or if you specify a lesser version of the language.

 


Table of Contents (Click this image ( ) to return here.)

Section

Summary

Associative Arrays

Javascript arrays are called "associative arrays". Learn what this term means in this section.

Setting Up an Array

Array creation is less simple in Javascript than in some other languages. In this section, learn how to create a new array.

Populating an Array

Once an array is created, its elements must be filled. Filling an array is discussed in this section.

Using an Array

Values in Javascript arrays can be accessed in more than one way. Learn how to do that here.

Working Example

Theory is nice but let's see some action. This example stores the hexadecimal values of the eight primary colors in an array. It looks them up upon choice from a list.


Associative Arrays

Associative arrays are X by 2 arrays; i.e, two dimensional arrays where the first dimension can be unlimited in size but the second dimension has a size of two. They consist of a list of "words" and "associated word" pairs. This might be translated into pairing types such as "keywords" and "definitions", "left" and "right" objects, or "number" and "meaning". Associative arrays should be familiar to users of Scheme and Lisp as "car" and "cat". VBScript calls this a dictionary. As a first example, let us examine a list of colors and their hexadecimal equivalents:

black

#000000

red

#FF0000

green

#00FF00

blue

#0000FF

magenta

#FF00FF

yellow

#FFFF00

cyan

#00FFFF

white

#000000

For every item in the left column, there is an associated item in the right column. This array has eight pairs. That is, it has a size of 8.

In Netscape 2.x, the first element (array[0]) of an associative array contained its size. Consequently, it we defined an array named hexColors, element 0 would contain "8", and elements 1-8 would contain the eight pairs which we just specified. Javascript arrays are also ordered. That is, if you could retrieve hexColor[2] and always obtain the same result. Current versions of Javascript/JScript now define an array property of length so you can get the size of the array with array.length. Note that Javascript arrays are zerobased. The colhex array has a length of nine. Interesting enough, although the 4.x browsers have no problem dealing with the old method of producing an array, they no longer put the length in 0. The way to accomodate old browsers is to put the length in the 0 element yourself.

If we wanted to obtain the hexadecimal equivalent for "blue", we could use

chex=colHex.blue

Back to Table of Contents


Setting Up an Array

In the Netscape 2.x browsers an array was just an object so an array was made as one makes all objects. A new instance of the array was created with the following script:

function MakeArray(n)
 {
        this.length = n;
        for (var i = 1; i <= n; i++)
        { this[i] = 0 }
        return this
  }

This function creates an array from a generic object, "this". Each element of the array is initialized to 0. Although this is not necessary, may be wise because otherwise the elements are undefined. In fact, this still works fine.

However, current browsers use the new statement to create an Array which is now a built in object in Javascript. Thus, the array in our example might be defined by

colHex=new Array(8)

Unfortunately, the meaning of this statement has altered between Netscape browser versions. In Javascript 1.1, it produced a new array with eight elements. In Javascript 1.2, it produced an array with one element which was set to 8. In Javascript 1.3, we are back to the 1.1 definition. Most of the time, you will not notice the difference, since setting the value of any element of an array expands the array to that size if it is not already big enough.

The function which follows, then, will make an array and fill it out to the length which you want. It also starts adding data at the one position and fills the 0 element with the length. You can easily modify this function to suit your own preferences.

function MakeArray(n)
 {
        var myarray = new Array(n)
								myarray[0] = n + 1
        for (var i = 1; i <= n; i++)
        { myarray[i] = 0 }
        return myarray
  }

Once the array object has been created, you may populate it.

Back to Table of Contents


Populating an Array

Since the array is ordered, we can fill the "left hand column" with statements such as

hexColors[1]="black"

By filling in the left hand column for an array element, we have defined a property of that array to be "black". In order to fill the "right hand column, though", we must use "object.property" notation; i.e., we will set the value of the property, "black".

colHex.black="#000000"

The entire array is filled with such pairs of statements.

colHex[2] = "red"
colHex.red = "FF0000"

An array notation such as found in C, Basic, or Pascal

colHex[2][1]="#FF0000"

will not work. You will not get an error but the 'property' will remain undefined.

In Javascript 1.2 and above, you can create an array with literal notation; i.e., you can define the elements of the array when you create it. For example,

colHex=new Array(9,'black','red','green','blue',magenta','yellow','cyan','white'

will produce the same array. However, we would still have to populate the right hand column.

Back to Table of Contents


Multidimensional Arrays

While an associative array has a lot of uses, the classical multidimensional array is missing from Javascript. Or is it? There is, in fact, no reason why one should not use the right hand column of an array to store another array. This makes for a kind of complex multidimensionality. It is, though, virtually impossible to store matrix like data. What you can have is an object-like structure. For example, a set of drawing tools might have colors, brushes, and papers. You could set up the initial array with

drawTools=new Array('colors','brushes','papers')

Now set up three new arrays:

colorNames=new Array(9,'black','red','green','blue',magenta','yellow','cyan','white')
brushNames=new Array('fine','medium','course',flat',irregular')
paperNames=new Array('plain','vellum','parchment',translucent')

As an example, we will fill the right hand values of the colorNames array with the RGB values.

colorNames.black='#000000'
colorNames.red='#FF0000'
colorNames.green='#00FF00'
colorNames.blue='#0000FF'
colorNames.magenta='#FF00FF'
colorNames.yellow='#FFFF00'
colorNames.cyan='#00FFFF'
colorNames.white='#FFFFFF'

Finally, set the right hand elements of the first array equal to the three new arrays.

drawTools.colors=colorNames
drawTools.brushes=brushNames
drawTools.papers=paperNames

You can now get the hex value of the blue color with

drawTools.colors.blue


Using an Array

We have already implied that there is more than one way to get at a 'property' value of an array object. Both of these statements will work:

If you want to retrieve a 'property' indirectly, you have to use the latter syntax with 'black' contained in a variable. For example, the lookup table below, uses this


This will also work:

This method called by the button below, which you might think would work, will give you 'undefined' as an answer

Further, if you mistakenly try to retrieve colHex[0].black, you will get an exception. This also returns an exception when the page is loaded.

aHex=colHex[1].['black'])

How do we retrieve the value of blue in the complex array, drawTools, which we defined above?

bluehex=drawTools.colors.blue

Back to Table of Contents


Working Example

Choose a color from the list to find its hexadecimal notation.

 

Selected Color

Hexadecimal notation for Color

The function is used to retrieve the hex value is as follows.

function doColor(alist)
{
  var aColor = ''
	 var ndx
	 ndx = alist.selectedIndex
	 aColor =alist.options[ndx].text
 	alist.form.selcol.value = aColor
 	var ahex = colHex[aColor]
  alist.form.hex.value= ahex
}

Note that we have passed this function the entire listbox. This enables us to find out any of the listbox properties as well as the form which holds it. We can then access any other controls in that form without knowing the form index or name.

Back to Table of Contents


This page has been accessed

times since March 8, 1999.