JavaScript Arrays

by George Freedrich.

Share
|
Homepage | Submit your article | Contact | TOS
More articles on ajax and javascript  

You are here: Categories » » AJAX and JavaScript

Because objects are collections of properties with each property having its own name and value, arrays are actually JavaScript objects. Each property in an array is an element, and each element can be assigned a value. One way to think of an array is as a collection of numbered variables.

An array in JavaScript has the following general formats for assigning values to elements:

sampleArr[0]=1; 
sampleArr[1]="ice cream"; 
sampleArr[2]=55 * (7 + alpha); 
sampleArr[3]= shootTheMoon(73); 
sampleArr[4]= otherArr[7]; 

or

sampleArr=new Array(1,"ice cream", (55 * (7+ alpha)), shootTheMoon(73), 
otherArr[17]); 

or, in JavaScript 1.2 or later:

sampleArr=[1,"ice cream", (55 * (7+ alpha)), shootTheMoon(73), otherArr[17]]; 

All three arrays are identical, using different methods for data assignment. The second two methods show the array to be more of an object, while the first method shows the variable-like characteristics of arrays.

In JavaScript, array elements begin with 0 and can be numbered sequentially or nonsequentially. In the second two previous examples, the first element is 0, and the other data separated by commas are numbered sequentially. However, you could have the following data assignment in an array:

alphaArr[0]= "uno"; 
alphaArr[7]= "dos"; 
alphaArr[345]= "tres"; 

Usually, arrays are numbered sequentially so that data can be added and extracted using loops. However, an array element can be called forth in any order and used just like a variable.

The data and data types that can be assigned to an array element are identical to the data and data types that you can assign to variables. You will also find that you can assign objects the same kinds of data. (Remember that an array is an object because it is composed for more than a single property.)

Setting Up an Array

Arrays are created using a constructor, just like other objects. The Array( ) constructor uses the following format:

var parts = new Array( );

Now, parts is an array object, and you can add data as in the following format:

parts[0]= "bolts"; 
parts[1] = "nuts"; 

As with declaring a variable, you need not enter data upon declaring the array, but you can. For example, you may declare and define a dense array using the Array( ) constructor:

var parts = new Array("bolts", "nuts", "washers", "screws"); 

You can also create an array using a dimension argument. If you know ahead of time how many elements are in your array, you can declare it and set a dimension for it at the same time. (In some languages, especially older ones, you are required to include a dimension for an array to reserve memory for your array.) For example, if you are creating an array of the U.S. Senate and you know that you have only 100 senators, you could declare and dimension your array as follows:

var senators= new Array(100); 

Once declared and dimensioned, you can add 100 elements, but the first senator would be this:

senators[0] 

The last would be this:

senators[99] 

You still get 100 elements, but you must begin with 0 instead of 1.

The declaration using a dimension argument is the exception to the rule that the first data value in a dense array (one in which the data are contained in parentheses) is considered element 0. Element 0 in the array will be the first data assignment after the declaration. For example, the following declaration first dimensions the array at 5 and then enters the first array element (0) as 7 in the next line:

var catWeights= new Array(5); 
catWeights(7,15,34,52,60); 

The numeric data value 5 is not a value of any of the array elements. It is the length of the array, with elements ranging from 0-4.

NOTE

I use the tag <script language="JavaScript"> without specifying the version number of JavaScript. You do not need to specify the version number to get the latest version of JavaScript supported by your browser. When using a dimension argument with Netscape Navigator 4 (NN4) and later, you will run into a bug if you specify <script language="JavaScript1.2"> and then attempt to dimension an array. NN4+ treats the declaration with the dimension value as the first value in the array instead of the length of the array. For example, try the following script:

<html> 
<head> 
<script language="JavaScript1.2"> 
var test= new Array(23) 
document.write(test.length); 
</script> 
</head> 
<body> 
</body> 
</html>

When you run the script using NN4 or later, a 1 appears on the screen. If you remove the 1.2 attribute from the <script> tag, the returned value is 23, the correct length. Because JavaScript 1.5 runs just dandy in Netscape Navigator 6 without specifying the version number in the <script> tag, and the latest version for Internet Explorer also runs well without specifying the version number, I prefer to leave out all version numbers as a habit. In this way, I can avoid bugs and span more JavaScript and browser versions.

A final way to declare an array using JavaScript 1.2 or later is called an array literal. The declaration uses brackets instead of parentheses and does not require the Array( ) constructor. The array object name is declared simply by assigning values to it within brackets, as the following script shows:

<html> 
<head> 
<script language="JavaScript"> 
var Lit= ["yes","no","maybe"]; 
document.write(Lit[2]); 
</script> 
</head> 
<body bgcolor=#face00> 
</body> 
</html>

The literal array Lit looks almost like a variable definition, were it not for the bracketed list of values. Using an array literal saves a couple of steps because no constructor is used, but older browsers (those before support of JavaScript 1.2) will not understand it as an array.

Array Properties and Methods

As an object, arrays have a single property, length, and several methods. However, Netscape Navigator 4 introduced five methods, Array.pop(), Array.push( ), Array.shift( ), Array.unshift( ), and Array.splice( ), that are not supported either by Internet Explorer or the EMCA-262 standard. To avoid problems but to be inclusive, I have placed the NN4+ array methods in a section to alert you to the fact that users of IE will not parse them correctly. Like all JavaScript enhancements not supported by the EMCA standards, I do not recommend using these methods for creating web sites that expect to have viewers using both major browsers.

Array Length

The single array property length returns the number of elements in an array. When using a loop, the test condition for the loop can be the length of the array so that you need not use an invariant value for the test. The format is as follows:

Array.length

The property is easily passed to a variable, as the following sample shows:

var dogs = new Array("Beagle","Terrier","Collie","Mutt"); 
var dogTail= dogs.length; 

The variable dogTail would have a length of 4 because four elements make up the array. The length property does not refer to the number of characters that make up the element in the array, but it refers to the number of elements themselves. Thus, the following array has a length of 2, even though more characters are used than in the first example with a length of 4:

var dogs = new Array("Greater Swiss Mountain Dog","Irish Wolfhound");
Concatenating the Elements of an Array: join(), toString(), and concat()

The Array.join( ) method takes all of the values in all of the elements in the array and creates one big string. For example, try out the following script:

joinArray.html
<html> 
<head> 
<script language="JavaScript"> 
var trees= new Array("Elm","Pine","Oak"); 
var bigBush=trees.join( ); 
document.write(bigBush); 
</script> 
</head> 
<body bgcolor=#ace007> 
</body> 
</html>

The results are the contents of the array minus the quotation marks, showing you Elm,Pine,Oak.

The Array.join( ) method accepts an argument that acts as a separator. Whatever you place in the join( ) parentheses within quotation marks replaces the commas. For example, change this line:

var bigBush=trees.join( ); 

to

var bigBush=trees.join(" and "); 

Then, launch the script again for a different result. The second results are Elm and Pine and Oak.

An older method from JavaScript 1.1 that is similar to the Array.join( ) method is Array.toString( ). The toString( ) method generates the same results as join( ), but you cannot specify the connecting characters between elements as you can with join().

A third method used for concatenating string elements in arrays is Array.concat(). Not only does the concat() method join all existing elements, but it also adds the elements in a concat() argument. For example, by changing the joinArray.html script slightly, you can see how it works.

concatArray.html
<html> 
<head> 
<script language="JavaScript"> 
var trees= new Array("Elm","Pine","Oak"); 
var biggerBush=trees.concat("Maple", "Sycamore"); 
var bigBush=trees.join(); 
document.write(biggerBush); 
alert(bigBush); 
</script> 
</head> 
<body bgcolor=#ace007> 
</body> 
</html>

A very important part of the concatArray.html script is that you can see that the Array.concat() method does not change the contents of the array. The array named trees still has only three elements. That is evidenced by the fact that the alert message shows only three elements, even though the variable bigBush was defined after the biggerBush variable was defined and added the Maple and Sycamore data to the mix. To add elements to an array, you assign new values to named elements. For example, to include the Maple and Sycamore data to the array, you could write this:

trees[3]="Maple"; // The fourth element is 3 since the first is 0 
trees[4]="Sycamore";
Changing the Order of an Array: sort() and reverse()

Two methods are available to change the order of array elements. The first sorts the array string elements alphabetically, and the second reverses their order.

The Array.sort() method is very simple, especially when using strings. After entering all of the strings in the array, you just enter the name of the array and method, and the array is ordered alphabetically. The following example shows both how the sort() method works and how array elements are extracted with a loop statement.

sortArray.html
<html> 
<head> 
<script language="JavaScript"> 
var zoo= new Array("zebras","lions", "apes","tigers"); 
zoo.sort( ); 
var newZoo=""; 
for(var counter=0; counter<zoo.length; counter++) {
newZoo += (zoo[counter] + "<br>") ; 
} 
document.write("<p>Alphabetical Animals<p>" + newZoo); 
</script> 
</head> 
<body bgcolor="lightsteelblue"> 
</body> 
</html>

All of the values are arranged in alphabetical order.

apes

lions

tigers

zebras

For ordering lists of any kind, you will find the Array.sort( ) method a handy tool.

The Array.reverse( ) method simply reverses the order of the data in the array. The first element becomes the last element, and everything else in the array is reversed as well. For example, the following:

var majorCities=new Array("Tokyo", "Los Angeles", "Paris", "Beijing", "Bloomfield") 
marjorCities.reverse( ); 

would return this:

Bloomfield, Beijing, Paris, Los Angeles, Tokyo

By using Array.sort( ) and Array.reverse( ) in concert, you can change ascending and descending orders of a sorted list.

Extracting Subarrays: slice()

To specify a subarray, use Array.slice( ). The general form of using slice( ) is shown here:

ArrayName.slice(begin,end) 

or

ArrayName.slice(begin to end) 

For example, if you have these statements:

computer=["Dell", "Gateway","Apple","IBM","HP"]; 
computer.slice(2,4); 

your return would be

Apple,IBM

Using a single argument takes the element from the argument to the end of the array as defined by the argument. For example:

computer.slice(2); 

would return

Apple,IBM,HP,

Negative numbers constitute a final type of argument used in the Array.slice( ) method. The negative value begins with the last element in the array as -1 and then counts backward toward the first element. For instance, the statement from the example in this section:

computer.slice(-1) 

returns this:

HP

Unlike the forward-counting slices that begin with 0, the last element in an array is identified as -1 using the slice( ) method with an array.

Navigator 4 Core Array Methods: pop(), push(), shift(), unshift(), splice()

This last set of methods adds a good deal of utility to working with arrays, and you can perform stack-like operations with the array. If you've ever written programs in Forth or written code for Adobe PostScript, you've worked with the stack, and pop( ) and push( ) are familiar. Each of the five is described briefly with a short explanation and is based on the following single example:

var stackWork= new Array("Lenny","Harold","Mary","Jean", "Sal");

Array.pop( ) removes the last element of an array and returns it.

stackWork.pop( ); returns Sal and removes it from the array. If a second identical statement were made on the next line, it would return Jean.

Array.push( ) adds a value to the end of the array (top of the stack) and leaves it there. By adding the following line, the string Delia would become the value to a new last element added to the array by the push( ) method:

stackWork.push("Delia"); 

In a pop( ) operation, it would be the first one off (LIFO-last in, first off).

Array.shift( ) removes the first element in an array and returns it. For example, this would return Lenny, remove it from the array, and shift the remaining elements to the left:

stackWork.shift( ); 

Element 0 would become Harold.

Array.unshift( ) is similar to the push( ) method, except that the new element is put at the front of the array (bottom of the stack). If you entered the following, the first element (element 0) in the array would have a value of Willie, the value Lenny would be shifted to the right into element 1, and so on for the entire array:

stackWork.unshift("Willie"); 

Finally, Array.splice( ) is a method used to insert, delete, and substitute values in array elements. The method has three arguments, start, delete, and data. The starting position specifies where the new value (data) is to be inserted and where deletions begin. If no deletions are specified, the splice( ) method has the effect of inserting an element and value into an array. For example, the following shows how to insert the value Fred into the second element, leaving the first as it is and shifting the rest to the right:

stackWork.splice(1,0,"Fred"); 

The splice( ) method allows you to insert elements, delete one or more elements, or change the value of an array element. You might find that these functions do not work in some of the older browsers, but IE5+ and NN4+ work well with them.

Leave a comment or ask a question
Total comments: 0

AJAX and JavaScript Disclaimer

  • The e-articles directory is not responsible for any and all copyright infringements by writers and authors. If you suspect the information contained by this page for any copyright infringements, please contact us to investigate the issue
JavaScript Variables - I like to think of variables as containers on a container ship. You can put all different types of content into the containers, move them to another port, empty them, and then replace the contain (more...)
JavaScript Operators - Operators can be placed into three categories-binary, unary, and ternary. Binary operators, most commonly associated with the concept of operator, take two (binary) expressions and combine them in (more...)
Loops in JavaScript - Loops in JavaScript are similar to loops in C++ and Java and most other languages using loop structures. In this section, you will find explanations of the different types of loops in JavaScript (more...)
Types of operators in JavaScript - Assignment Operators The key assignment operator is the equals sign (=). The left operand is a variable, an array element, or an object property, and the righ (more...)
Conditional Structures - The "thinking" structure in JavaScript is found in the different types of conditional statements in the language. Used in concert with different types of comparative operators, conditional statem (more...)
The ''with'' Statement - Like the ternary conditional operator, the with statement is a shortcut. Instead of having to list all of the properties of an object by repeating the basic object, you can state the bulk (more...)
Operators Precedence - The order in which expressions are evaluated based on their operators is known as precedence. Multiplication and division occur before addition and subtraction, so any operands that are to be mul (more...)
Nested Loops, label and continue Statements - The label statement does not inherently go with the continue statement but, like discussing break with switch and case, you might find it useful to se (more...)
Advantages and Disadvantages of AJAX Techniques ~ AJAX Without XMLHttpRequest - There are a number of cases in which you might not have XMLHttpRequest support. The most common would be in the case of an older browser. This is the hardest to work around, not because there (more...)
AJAX Usability Guidelines - Many usability experts have criticized AJAX by pointing out cases where it hurts usability. Although it is possible for AJAX to have that effect, I don't think AJAX inherently hurts usability; (more...)

 
free content
    Copyright © 2006 - 2012 e-articles.info.
The texts, articles and tutorials in the directory are property of their respective owners and authors.