Associative Arrays

<font color="red" size=4>WebTV JS "Bug" -Reload Page (cmd-r)</font>


By way of review, it will be recalled that arrays may be defined in two ways, either by explicitly assigning values to each location

enrollee=new Array();
enrollee[0]="Mike";
enrollee[1]="Jill";
enrollee[2]="Sam";
enrollee[3]="Mary";

or by writing the values in order when declaring an arrayenrollee=new Array("Mike","Jill","Sam","Mary");There is another way as well which is closely related to assigning properties to an object. It as called an associative array and rather than being indexed by 0, 1, and so on the elements are given names. For example, a student in a classroom can be identified by the associative array:
        enrollee=new Array()
        enrollee["name"]=name;
        enrollee[midterm"]=midterm;
        enrollee["finl"]=finl;
where the italics represent values that are assigned. In this instance, as with random access by entering an index, typing in the word used as an index,"entry", provides the value of that particular element. With the array already defined, one is basically setting the value of an output variable:

content=enrollee[entry];


Here is one way to make use of this:



/* Make Array */enrollee=new Array();
enrollee["name"]="Whoever";enrollee["midterm"]="Midterm Grade: ?";
enrollee["final"]="Final Grade: ?";
enrollee["comment"]="Whatever";

/* Main Program - Show an Element */
entry=prompt("Put in index word");
content=enrollee[entry];
alert(content);


An operational example is shown below:



It must be emphasized. There is no setting of an integer index according to the word entered to obtain the array element. It is the word entered itself which is the index.

This is a useful aspect of JS, since variables in functions are stored implicitly as arrays. In consequence, when an object is created using a constructor function, the value for any of its properties can be obtained by just entering the word used for the property. For example,

/* This creates an object the properties for
which are elements of the calling variable */
function student(){
this.name=prompt("Enter Student Name");
this.midterm=prompt("MidTerm Grade for:"+this.name);
this.finl=prompt("Final Grade for: "+this.name);}

/* This displays any object property listed */
function reprt(){
entry=prompt("Enter word: name, midterm, or final");
enrollee[entry]=alert(entry+" "+enrollee[entry]);}

/* This is the Main Program */
enrollee=new student();reprt();



As should be now evident, though an array has not been explicitly defined in the function, one is there nevertheless. In this instance it is an associative array. If a misspelling has been noted, finl" instead of "final", it is because "final" cannot be used as a variable, but it can be used as an index since it is in quotes.

JS Test-Bed 1 - - JS Test-Bed 2


<< PreviousNext >>