reptile7's JavaScript blog
Wednesday, June 28, 2006
 
Array Miscellaneous
Blog Entry #43

I was at my local Starbucks, sipping a venti dark roast as is my custom, thinking about JavaScript arrays, and I wondered, "Just what is the scope of these things? What all can we organize as an array?" In the Primer #26 Script, we created an array of text strings. Recalling Netscape's array definition - "an ordered set of values that you refer to with a name and an index" - it should be clear that we can create arrays of other types of values; for example, we can create an array of numbers:

squares = new Array(1,4,9,16,25,36,49,64,81,100);

Or an array of Boolean values:

tralse = new Array(false,true,false,true,true,false);

Or even an array of the null and undefined primitive values:

dontknow = new Array(null,undefined,undefined,null);

What else? Given the connection between arrays and variables, it occurred to me that anything that can be variabilized, directly or indirectly - properties, objects, methods, whatever - should be arrayable.

Property arrays

"Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure," Netscape notes in the "Objects and Properties" section of Chapter 7 ("Working with Objects") of its JavaScript 1.5 Core Guide. In illustration, consider the image element coded below:

<img name="myImage" width="150" height="150" border="0" src="some_image.gif">

For this image, we can easily create an array of properties that is manipulable by the methods of the Array( ) object:

<script type="text/javascript">
imgprop = new Array( );
imgprop[0] = document.myImage.border;
imgprop[1] = document.myImage.height;
imgprop[2] = document.myImage.name;
imgprop[3] = document.myImage.src;
imgprop[4] = document.myImage.width;
</script>

Method example
We can reverse the order of the imgprop elements with the reverse( ) method:

imgprop.reverse( );
window.alert(imgprop[4]);
// the alert( ) box displays 0, as document.myImage.border is now imgprop[4]

Object arrays

The following objects are constructible (i.e., can be created with a constructor statement) and are thus arrayable:
Built-in JavaScript objects*: Array, Boolean, Date, Function, Number, Object, RegExp, String
DOM host objects: Image**, Option
(*The built-in Math object is not constructible; an optimistic attempt to execute a mathtest = new Math( ) statement met with an error.)
(**We will discuss the new Image( ) constructor in Primer #27.)

For example, we can create an array of Date objects:

beatbirth = new Array( );
beatbirth[0] = new Date("July 7, 1940"); // octopus
beatbirth[1] = new Date("October 9, 1940"); // walrus
beatbirth[2] = new Date("June 18, 1942"); // obladi
beatbirth[3] = new Date("February 24, 1943"); // taxman

In applying the Array( ) object to host objects, we are not limited to the image and option objects. We learned in Blog Entry #26 that newly opened windows can be variabilized; we can thus create an array of windows - and by extension, an array of the documents they hold - as follows:

winx = new Array( );
winx[0] = window.open(URL0);
winx[1] = window.open(URL1);
winx[2] = window.open(URL2);
winx[3] = window;
// winx[3] references the opener window; winx[3] = window.opener would throw an error

Pushing the envelope a bit further, it would seem that any referenceable document element can be an Array( ) element. Consider a document containing the following three forms:

<form name="f00">
<input name="c00" value="Text box #1"><br>
<input name="c01" value="Text box #2"><br>
</form>
<form name="f01">
<input type="button" name="c02" value="Button #1"><br>
<input type="button" name="c03" value="Button #2"><br>
</form>
<form name="f02">
<select name="c04">
<option>Option #1</option>
<option>Option #2</option>
</select></form>

As you know, the f00, f01, and f02 forms compose the document.forms[i] array. However, we can certainly create a separate array of these forms using the Array( ) object if for some reason we wanted to do that:

formx = new Array( );
formx[0] = document.f00;
formx[1] = document.f01;
formx[2] = document.f02;

We can similarly create an Array( ) of the f00, f01, and f02 form controls; it is left to the reader to write out the code therefor.

Method arrays

Some methods output values and thus can be arrayed, for example:

prox = new Array( );
prox[0] = window.prompt("Do you prefer vanilla or chocolate ice cream?");
prox[1] = window.prompt("Do you prefer coffee or tea?");
prox[2] = window.prompt("Do you use a PC or a Mac?");
window.alert(prox.join("/"));
// the join( ) method of the Array( ) object is outlined here

Try it out:


However, method commands that don't return values are still indirectly arrayable via the built-in Function( ) object. In JavaScript, methods are in fact a subset of functions - "[a] method is a function associated with an object," Netscape declares in its "Defining Methods" documentation. The code below creates an array of specific window.alert( ), document.write( ), and text_object.focus( ) commands:

meth = new Array( );
meth[0] = new Function("window.alert('Hello, world!');");
meth[1] = new Function("document.write('Laissez les bons temps rouler!');");
meth[2] = new Function("document.f00.c00.focus( );");

Etc.

Associative arrays

Although array elements are indexed automatically with ordinal numbers, we can also index them with strings:

array_name = new Array( );
array_name["string0"] = value0;
array_name["string1"] = value1; // etc.

Such arrays are termed associative arrays "because each index element is also associated with a string value," quoting Netscape. We had a brief taste of associative arrays in Blog Entry #32 when we noted that an <img name="imagename"> element can be referenced with document.images["imagename"].

An associative array is put to creative use in the guitar chord script discussed in HTML Goodies' JavaScript Script Tips #56-59.

Two-dimensional arrays

In the previous post, I drew a parallel between arrays and mathematical matrices; making the connection more explicit is the fact that arrays can be two-dimensional. (And Netscape's sample code is clearly extensible to the construction of higher dimensional arrays.) I'm not inclined to talk about 2D arrays here and now but will note that a 2D array figures prominently in the "pop-up tables" script discussed in HTML Goodies' JavaScript Script Tips #92-93.

More Array( ) method demos

The "Arrays" section of HTML Goodies' recently posted "JavaScript Basics Part 5" article sports several Array( ) method demos that are worth checking over. (Make sure your browser is up-to-date! Specifically, if you're using a pre-5.5 version of Internet Explorer, then the push( )/splice( ) and pop( ) demos won't work for you.)

We'll continue "putting it all together" in the next post as we examine HTML Goodies' JavaScript Primers #27, in which we'll code a simple slide show. Who needs PowerPoint, anyway?

reptile7

Comments: Post a Comment

<< Home

Powered by Blogger

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)