Arrays

Often we need to work with many pieces of data, rather than just a single number or string.

For example, to compute the average high temperature for a month, we need the high temperature for each day.

Collections of multiple data values can be stored in a list, also known as an array.

// A single value
temperature = 72.1;

// Many values
temperatures = [ 72.1, 68, 77.7, 90.2, 61.0 ];

Each entry in an array has an index - the first is # 0, the second is 1, third is 2, etc.
To access one entry, use square brackets and the index. eg temperatures[2] means just the third entry (the value 77.7 in the example above).






Arrays

Often we use a loop to access all elements in a list, one after the other.

// Write all the temperatures
i = 0;
while (i < temperatures.length)
    {
    document.write(temperatures[i] + "<br>");
    i = i + 1;
    }





Arrays

Every array has a ".length" property, telling you how many entries it has.

There are also several built-in functions. Some useful ones:

Strings

Strings are like arrays of characters.

s = "abcdef";
// This will display the letter "c"
alert(s[2]);


Creative Commons License
This document is by Dave Pape, and is released under a Creative Commons License.