Some Processing with User Defined Arrays

 

User Defined Arrays.  I have been unable to find anything about higher dimensional arrays in JavaScript so I am restricting this discussion to user defined one-dimensional arrays.  Working with user defined arrays is essentially the same as working with built-in arrays.  The two major differences have to do with initially defining them and initially assigning values to the elements of the array.  We will work two different examples, one where the array is defined and initialized all at once and the other where it is initialized after it has been defined.

Strobing Colors.  Our first example doesn't work as nicely as I would like, but it gives us something to improve on in later chapters.  The code simply sets up an array of colors and then loops through the array to change the background color of the page when the user clicks on a button.

You should copy the following code and put it in a file called StrobeColor.html.

 

<html>
<head>
<title>Strobe Colors</title>
<script language="JavaScript">
function StrobeIt()
{
var rainbow_colors= new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");


for (var i = 1; i <=10; i++)
{

var index = 0;
while (index < rainbow_colors.length)
{

window.document.bgColor = rainbow_colors[index];
index++;

}

}
</script>
</head>

<body>
<form>
<input type="button" value="Strobe Color Background" onClick="StrobeIt();">
</form>
</body>
</html>

 

When this is uploaded you should get something like the following before you click on the command button.

 

 

Once you click on the button the page should have a strange variation in color ending in solid violet.  I have nested the color changes in a double loop to make sure it goes through the array of colors more than once.

Get the Picture.  The next example also works with a one-dimensional array.  The elements are filled in based on some modulo arithmetic.  That is, if the remainder of the index divided by three is equal to one then the array element gets an "X".  Otherwise it gets a "0".  Then the array is printed out in a block rather than in a row.

You should call the file GetThePicture.html.

 

<html>
<head>
<title>Print the Picture</title>
<script language="JavaScript">
function printArray( )
{
var picture_array = new Array();
// filling in the array
for (var i = 1; i <=63; i++)
{

if (i % 3 == 1)
{

picture_array[i] = "X";

}

else
{

picture_array[i] = "0";

}

}

// printing out the array
for ( var i = 1; i <= 7; i++)
{

for ( var j = 1; j<= 9; j++)
{

window.document.writeln(picture_array[i+j-1]); 

}
window.document.writeln("<BR>"); 

}
}
</script>
</head>

<body>

<form>
<input type="button" value="Get the Picture" onClick="printArray();">

</form>

</body>
</html>

 

After uploading the page and clicking on the command button you should see something like the following array.  Remember, we are using creative printing to display a one-dimensional array as a two-dimensional array.