Using Arrays

[ LiB ]

Using Arrays

An array is an indexed list of values that can be referred to as a unit. Arrays can contain any type of value. Before you can use an array, you must first declare it. The following example shows how to create an array that will hold 10 strings that contain information about an automobile inventory.

 Auto = new Array(10); Auto[0] = 98 Ford Explorer; Auto[1] = 97 Ford Explorer; Auto[2] = 85 Plymouth Mustang; Auto[3] = 96 Plymouth Voyager; Auto[4] = 90 Honda Civic; Auto[5] = 97 Honda Civic; Auto[6] = 96 Plymouth Neon; Auto[7] = 98 Plymouth Neon; Auto[8] = 92 Ford Explorer Wagon; Auto[9] = 95 Honda Civic Hatchback; 

The first statement uses the new keyword to create an Array object named Auto that will contain 10 entries. The rest of the statements assign string values to the array. As you can see, the array's index starts with 0 and goes to 9.

Defining an Array

The following script uses the preceding array example to demonstrate how to display an array element by using the document.write() statement with the element's array name and index number.

 <HTML>   <HEAD>   <TITLE>Script 2.22 - Sample Array</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">      <!-- Start hiding JavaScript statements       Auto = new Array(10);       Auto[0] = "98 Ford Explorer";       Auto[1] = "97 Ford Explorer";       Auto[2] = "85 Plymouth  Mustang";       Auto[3] = "96 Plymouth Voyager";       Auto[4] = "90 Honda Civic";       Auto[5] = "97 Honda Civic";       Auto[6] = "96 Plymouth Neon";       Auto[7] = "98 Plymouth Neon";       Auto[8] = "92 Ford Explorer Wagon";       Auto[9] = "95 Honda Civic Hatchback";       document.write("The first element in the array is a <B>", Auto[0], "</B>");     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.13 shows the results of loading the previous example. In this case, the first array element, Auto[0], is displayed.

Figure 2.13. Array elements can be individually extracted by referencing their index number in the array.

graphic/02fig13.gif


Processing Arrays with for Loops

In this next example, we'll use a for loop to traverse the entire array and display all of its contents. The loop begins at the beginning of the array, Auto[0] , and uses an increment of 1 to step through the elements of the array until it reaches the end. To determine the end of the array, the script creates a variable called arrayLength and sets its value equal to the array length property, which in this example is 10.

 <HTML>   <HEAD>   <TITLE>Script 2.23 - Looping through an Array</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var arrayLength;       Auto = new Array(10);       Auto[0] = "98 Ford Explorer";       Auto[1] = "97 Ford Explorer";       Auto[2] = "85 Plymouth Mustang";       Auto[3] = "96 Plymouth Voyager";       Auto[4] = "90 Honda Civic";       Auto[5] = "97 Honda Civic";       Auto[6] = "96 Plymouth Neon";        Auto[7] = "98 Plymouth Neon";       Auto[8] = "92 Ford Explorer Wagon";       Auto[9] = "95 Honda Civic Hatchback";       arrayLength = Auto.length;       document.write("<B>Current Inventory Listing</B><BR>");       for (var i = 0; i < arrayLength;i++) {         document.write(Auto[i], "<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.14 demonstrates how the for loop was able to process every array element.

Figure 2.14. A for loop enables you to read the entire contents of an array.

graphic/02fig14.gif


Dense Arrays

You can also create dense arrays. A dense array is one that is populated at the time it is declared. This is a very efficient technique for creating small arrays. The following example shows you how to create a dense array named animals that consists of five entries. The array will have the following structure:

 animals = new Array("mice", "dog", "cat", "hamster", "fish"); 

After creating the array, the script prints its contents using a for loop and the Animals.length property.

 <HTML>   <HEAD>     <TITLE>Script 2.24 - A Dense Array</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       var arrayLength;       Animals = new Array("mice", "dog", "cat", "hamster", "fish");       arrayLength = Animals.length;       document.write("<B>List of animals in the Zoo</B><BR>");       for (var i = 0; i < arrayLength;i++) {         document.write(Animals[i], "<BR>");       }     // End hiding JavaScript statements -->      </SCRIPT>   </BODY> </HTML> 

Figure 2.15 shows the results of loading this example into your browser. Each array entry is listed beginning at index 0 and going through to the end of the array.

Figure 2.15. The result of a dense array

graphic/02fig15.gif


Sorting Arrays

Arrays have a sort () method you can use to sort their contents. The following example shows how to display a sorted list of the contents of an array. The script first defines a dense array with five entries. Next, it displays a heading, and it then uses the sort() method inside a document.write() statement to display the sorted list. Notice that I did not have to create a for loop to step iteratively through the array's index. The sort() method took care of this for me.

 <HEAD>   <TITLE>Script 2.25 - Sorting an Array</TITLE> </HEAD>    <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       Animals = new Array("mice", "dog", "cat", "hamster", "fish");       document.write("<B>List of animals in the Zoo</B><BR>");       document.write(Animals.sort());     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

Figure 2.16 shows the results of loading the previous page into your browser. Note that the result of the sort() method is a list displayed on a single line, with the elements in the array separated by commas.

Figure 2.16. The array's sort() method provides an efficient way of sorting the elements of the array.

graphic/02fig16.gif


Populating Arrays with Dynamic Data

You can create scripts that enable users to supply them with their data, as opposed to hard coding it into the script. For example, the following script prompts users to type their three favorite things and then creates an array to contain the list.

The script uses a for statement to control program execution. Each time the loop executes, it asks the user to type a response and assigns the response to the array by giving it the next available array index number (as designated by the current value of i ).

 <HTML>   <HEAD>     <TITLE>Script 2.26 - Building a dynamic Array</TITLE>   </HEAD>   <BODY>     <SCRIPT LANGUAGE="JavaScript" TYPE="Text/JavaScript">     <!-- Start hiding JavaScript statements       document.write("What are your 3 most favorite things? <BR>");       NumberArray = new Array(3);       for (var i = 0; i < 3;i++) {         var yourNumber = prompt('I like: ', ' ');         NumberArray[i] = yourNumber;         document.write(NumberArray[i], "<BR>");       }     // End hiding JavaScript statements -->     </SCRIPT>   </BODY> </HTML> 

NOTE

TIP

The preceding example shows you how to write a script that enables the user to populate its contents dynamically rather than requiring you to hard code in its contents. Another way to work with an array dynamically is by increasing its length during script execution.You can extend the size of an array by adding new array elements with an index number that is higher than the last index number in the array. For example, if I were to declare an array with an index of 50, I could later expand the array by adding a new array element with an index number of 99.This would increase the size of the array to 100.

Figure 2.17 shows the results of loading the previous example into your browser. As you can see, the heading is displayed followed by the contents of the new array.

Figure 2.17. Dynamic arrays make it possible to show the contents of an array that the user just populated.

graphic/02fig17.gif


[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net