Tuesday, December 14, 2010

JavaScript Array Basics

Learn how to use JavaScript arrays. In this tutorial you learn what a JavaScript array is, how to create an array, how to access an array's contents, how array lengths work, and how to loop through arrays.
Like most languages, JavaScript lets you create arrays to store bunches of values in. Anarray is simply a sequence, or list, of values. A value in a JavaScript array can be anything from a number or string, through to a function or an object; JavaScript arrays can store pretty much any type of data. A single value in a JavaScript array is called anelement.
With JavaScript arrays, you can:
  • Store any number of values, including no values at all (known as an empty array)
  • Access any or all the elements of an array through a single variable name
  • Read and write elements of an array
  • Loop through all the elements of an array
  • Join two or more arrays together to make one longer array
  • Convert an array to one long string
  • Add or remove elements from the beginning, end, or middle of an array
  • Reverse the order of the elements in an array
  • Sort the elements of an array in any order you like
  • Nest arrays within other arrays
JavaScript stores arrays as Array objects, so most of the things you can do with arrays revolve around the properties and methods of the Array class.
In this introductory article, you look at creating arrays, accessing the contents of arrays, the concept of array lengths, and looping through arrays.
Actually there is an upper limit on the number of elements in an array, but since that limit is 4,294,967,295, you probably won't come across it very often!

Creating a JavaScript array

There are many ways to create a JavaScript array. For example, you can use an array literal, as follows:

// Create an empty array
var emptyArray = [ ];

// Create an array of fruit
var fruits = [ "apple", "pear", "orange", "banana" ];
literal is a fixed value that you type directly into your code.
You can also create a new Array object:

// Create an empty array
var emptyArray = new Array ( );

// Create an empty array that's 15 elements long
var emptyElementsArray = new Array ( 15 );

// Create an array of 1 element
var myName = new Array ( "Matt" );

// Create an array of fruit
var fruits = new Array ( "apple", "pear", "orange", "banana" );
The array you create depends on the number and type of values you pass to theArray constructor. Supplying no values produces an empty array of zero length. Passing a single numeric value creates an empty array of that length. Passing more than one numeric value, or one or more non-numeric values, creates an array containing those value(s) as individual elements.
You're not limited to passing literal values to the Array constructor. For example, you can create an array containing the values of some variables:

var favouriteFruit = "banana";
var favouriteColour = "red";
var favouriteNumber = 8;

var favourites = new Array ( favouriteFruit, favouriteColour, favouriteNumber );

The above code produces the following array:

[ "banana", "red", 8 ]
You can even create arrays of functions and objects. For example, the following (rather pointless) array contains the DOM window object, the DOM document object, and theString.unescape() function:

var randomStuff = new Array ( window, document, unescape );
If you create an array by passing in numeric or string variables, the array contains copies of those variable's values. For example, if you changedfavouriteColour to "blue" after creating the favourites array in the above example, the value inside the array would still be "red".
However, if you create an array of functions or objects, the array containsreferences to those functions or objects. For example, if you change an object in an array by referencing it elsewhere, the object inside the array is also changed (because it's actually the same object).

Accessing the contents of an array

Each element in an array is given an index, which is an integer value between 0 and one less than the length of the array. The first element has an index of 0, the second element has an index of 1, and so on.
To access an element, use the syntax:

arrayName[index]
For example, using our favourites array that we created above:

alert ( favourites[0] );
alert ( favourites[2] );
...produces 2 alert boxes with the values banana and 8 respectively.
As well as reading array elements, you can also write to array elements in a similar fashion. For example:

favourites[0] = "apple";
...changes the first element of the favourites array from "banana" to "apple".

Understanding array lengths

To retrieve the length of an array, use its length property, as follows:

var fruits = new Array ( "apple", "pear", "orange", "banana" );
alert ( fruits.length ); // Displays "4"
The length of an array isn't necessarily the same as the number of elements in an array. For example, the following array has a length of 15, but it only contains a single element:

var myArray = new Array ( 15 );
myArray[0] = "myValue";
You can also set an array's length at any time:

myArray.length = 50;
  • If you set an array's length to be greater than its current length, no new elements are created; the array merely ends up with a longer length property.
  • If you set an array's length to be less than its existing length, you shorten the array'slength property. In addition, any elements with indices that fall outside the new array length are discarded.
You can also increase the length of an array by adding a new element with an index greater than or equal to the array's current length. The example below changesmyArray's length from 15 to 100:

myArray[99] = "anotherValue";
If you set an array to be a certain length, all values within the array that have not been explicitly defined have the value undefined. So in the above example, myArray[0]contains "myValue", and myArray[1] – myArray[99] all contain the value undefined.

Looping through arrays

One of the most useful things about a JavaScript array is that you can use a loop to move through each element of the array in turn. Consider this non-looping example, which displays each of the six fruits in the fruits array in turn:

var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );

alert ( fruits[0] ); // Displays "apple"
alert ( fruits[1] ); // Displays "pear"
alert ( fruits[2] ); // Displays "orange"
alert ( fruits[3] ); // Displays "banana"
alert ( fruits[4] ); // Displays "peach"
alert ( fruits[5] ); // Displays "strawberry"
As you can imagine, this starts to become unwieldy when you have a lot of elements in your array.
Here's how to do the same thing with a for loop:

var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );

for ( i=0; i < fruits.length; i++ )
{
alert ( fruits[i] );
}
Not only is the loop version more compact, but you can use it to handle any number of array elements without needing to change the code.

Recommended reading

If you want to get serious with JavaScript, you'll get a lot fromJavaScript: The Definitive Guide. Like most O'Reilly books, it's comprehensive, yet approachable. While not aimed at the absolute beginner, if you've already played around with JavaScript then this book is a great way to take your skills to the next level!
Buy from Amazon.com | Amazon.co.uk

Further reading

Now that you know the basics of JavaScript arrays, take a look at Manipulating JavaScript arrays, which explains how to extract portions of an array; how to join arrays together; how to convert an array to a string; and how to add and remove elements from an array.
The Mozilla Developer Center has a good reference covering the Array class. W3Schools also summarizes Array's methods and properties and provides some handy examples that you can try out.

No comments:

Post a Comment