JavaScript Arrays

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
JavaScript History ObjectJavaScript Timeouts


Purchase and download the full PDF version of this JavaScript eBook for only $8.99


In Introducing JavaScript Variables and JavaScript Variable Types we looked at storing data (such as numbers, strings and boolean true or false values) in memory locations known as variables. The variable types covered in those chapters were useful for storing one value per variable. Often, however, it is necessary to group together multiple variables into a self contained object. This is where the concept of JavaScript Arrays comes in.


Contents


What is a JavaScript Array

A JavaScript array is an object that contains a number of items. Those items can be variables (such as strings or numbers) or even other objects (such as Image objects or custom objects which you as a JavaScript developer have created). Once you have grouped all the items into the array you can then perform tasks like sorting the array items into alphabetical or numerical order, accessing and changing the value assigned to each array item, and passing the group of items as an argument to a JavaScript function (see Understanding JavaScript Functions) by passing just the array object.

In this chapter we will look in detail at how to create and manipulate JavaScript arrays.

How to Create a JavaScript Array

A new instance of a JavaScript array object is created in the same way as any other object in JavaScript using the new keyword. For example we can create a new array object instance called myColors as follows:

var myColors = new Array();

We can also specify the initial size of the array when we create it by passing through the number of elements that we require the array to hold as an argument to the Array() object constructor. For example, to initialize an array to hold 7 items:

var myColors = new Array(7);

Note: An array will grow automatically as new items are added so it is not necessary to specify at creation time the number of elements you believe the array will need. The decision as to whether to pre-allocate the initial size of the array is typically one of memory and speed. A mission critical application that needs to store a large amount of data in an array may not want the delay associated with waiting for the size of the array to be increased each time a new item is added. In this situation the array would be pre-initialized by specifying an initial size. This then has the trade-off that a large amount of memory may be taken up and not used right away. In practice it is usually acceptable to let arrays grow as items are added.


Initializing the Elements of an Array

Before looking at how to add items to an array it is important to understand how arrays are indexed. The first item in an array is item 0, the second is item 1 and so on.

There are a number of different ways to initialize an array. One way is to specify the initial items at creation time by passing through the items as arguments to the the Array() constructor:


var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");

Another mechanism is to assign an item to each array element slot using an index value surrounded by square brackets:


var myColors = new Array();

myColors[0] = "Red";
myColors[1] = "Green";
myColors[2] = "Indigo";
myColors[3] = "Violet";

Any time you need to change the value of an array element the same approach applies. For example, to change the second element of the array from "Green" to "Yellow":


myColors[1] = "Yellow";

Another useful way to add elements to an array is to use the push() method of the array object. The push method simply adds a new element to the end of the array:


var myColors = new Array();

myColors.push ("Red");
myColors.push ("Green");
myColors.push ("Indigo");
myColors.push ("Violet");

Accessing the Elements of a JavaScript Array

Any element of an array can be accessed by referencing the index into that array. For example, the following JavaScript will display the 3rd element of our myColors array (remembering that the first element is index 0) and display the string "Blue":

var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");

document.write ( myColors[2]);

Often, however, it is necessary to access each element in an array. While writing code to access each item one by one is acceptable for an array with only a few items, this becomes difficult for larger arrays. Fortunately there are a couple of ways to loop through all the items in the array.

One way is to create a for loop (see JavaScript Flow Control and Looping) combined with the length property which contains the number of items in the specified array. The following example creates a for loop that will display each item in the array until the number of items in the array is reached:


for (var i = 0; i < myColors.length; i++)
{
      document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}

JavaScript provides an even easier way to access each element in an array using the for in syntax. This essentially performs the same function as the above for loop but with a little less typing:


for (i in myColors)
{
      document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}

JavaScript Array Object Methods and Properties

Given that the JavaScript Array is an object it should not be surprising to learn that it contains properties and methods that allow you, as a JavaScript developer, to perform powerful tasks with the data in the array. The following table describes these methods and properties:

MethodDescription
concat()Concatenates the elements passed into an array
join(separator)Joins together all the elements in an array to produce a single string. If no separator argument is passed through a comma is assumed.
pop()Deletes the last element added to the array - the opposite of push()
push()Adds a new element to the end of the array - opposite of pop()
reverse()Reverses the order of the elements in the array
shift()Deletes the first element in the array and shifts the remaining elements down to fill the empty slot
slice(begin, end)Returns a subsection of the array based on the begin and end index arguments. The end argument is optional. If omitted the end of the array is assumed.
sort()Sorts the elements of an array into alpha or numerical order
splice()Inserts and removes elements from an array
unshift()Adds an element to the front of the array

The main properties of the Array object are as follows:

PropertyDescription
lengthContains the length of the array
prototypeProvides a mechanism for JavaScript developers to add their own properties to the array object

JavaScript Array Sorting

As an example of using the methods of the array object we can look at sorting the elements in our myColors array. For example:


var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");

for (i in myColors)
{
      document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}

The above script will output the colors in the order in which we added them to the array:

myColor[0] = Red
myColor[1] = Green
myColor[2] = Blue
myColor[3] = Indigo
myColor[4] = Violet

If we sort the array using the sort() method before printing out the element however:


var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");

myColors.sort();

for (i in myColors)
{
      document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );
}

we get the following output with the colors sorted alphabetically:

myColor[0] = Blue
myColor[1] = Green
myColor[2] = Indigo
myColor[3] = Red
myColor[4] = Violet


Purchase and download the full PDF version of this JavaScript eBook for only $8.99



PreviousTable of ContentsNext
JavaScript History ObjectJavaScript Timeouts