1. Computing

JavaScript By Example

Objects: 4. Array

By

The Array object provides the means to collect a number of identical variables or objects together into a single object to make them easier to process. Of all of the built in objects the Array object probably has the greatest number of methods available for manipulating the content of the array with methods to add and delete entries from the front, end or anywhere else in the array, the ability to sort an array using whatever sort criteria you like, and other things relating to manipulating collections of identical objects.

As with Objects there is a shortcut notation available for creating arrays and so you can wrap all of the entries in [] instead of specifying new Array(). The entries in the array can be set when defining the array by including them as a comma separated list or they can be individually set or accessed afterwards by referencing a specific position within the array (the first position in the array is position 0 and the second is 1 etc.).

Note that while you can use array notation with names rather than numbers to reference the contents (what is known as an Associative Array), JavaScript actually treats those as referencing an Object rather than an Array and so the Array methods are not available to use with collections referenced that way.

In this example we combine an Array with the Date we looked at in the last example in order to retrieve the month name. The Date works with month numbers between 0 and 11 because it expects you to mainly use it for this type of array lookup and the entries in our example array are month[0] through month[11].


var today,month, txt;
today = new Date();
month = ['Jan','Feb','Mar','Apr','May','Jun',
  'Jul','Aug','Sep','Oct','Nov','Dec'];

txt = 'It is ' + month[today.getMonth()];

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Objects
  7. JavaScript By Example - Objects: Array

©2014 About.com. All rights reserved.