Week 10: Demo

Arrays



Array Basics

Arrays are variables that can hold a list of values. This is very useful if you have a bunch of the same type of something (e.g.: people's names, image file names, color values, booleans, objects, etc). There are a couple different ways that we can declare and define arrays. Here are two ways to create empty arrays:

var arrayName = new Array();
var arrayName = [];

We can also define a new array with some initial values. Here are some arrays with three initial string values:

var arrayName = new Array("first thing", "second thing", "third thing");
var arrayName = ["first thing", "second thing", "third thing"];

Here are some numeric values:

var arrayName = new Array(4, 8, 15, 16, 23, 42);
var arrayName = [4, 8, 15, 16, 23, 42];

Here are some boolean values:

var arrayName = new Array(true, false, true, true, false);
var arrayName = [true, false, true, true, false];

Writing to arrays is fairly straight forward. All arrays have indexes that are the numeric address where the value is stored in the array. These arrays are always in sequential order, and always begin at 0. We can assign values to these indexes manually by referring directly to the number of the index using the square bracket syntax.

arrayName[0] = "first thing";
arrayName[1] = "second thing";
arrayName[2] = "third thing";

We can read the number of elements being stored in an array by using the length property.

console.log(arrayName.length);

Parallel Arrays

We can store multiple properties that are associated with each other across different arrays. We keep these properties associated by making sure they use the same number index across the different arrays. There's nothing to maintain their alignment other than your manual entry of the values to the arrays.

var firstName = [];
var lastName = [];
var email = [];

firstname[0] = "Aaron";
lastname[0] = "Siegel";
email[0] = "aaronsie@usc.edu";

firstname[1] = "Steve";
lastname[1] = "Child";
email[1] = "child@usc.edu";

firstname[2] = "Patrick";
lastname[2] = "Dent";
email[2] = "dent@usc.edu";

Dynamic Page Content Using Arrays

We can store a bunch of different properties and dynamically access them from an array. In the example below we will store a an array of image file names and then use the Math.random() function to generate a number within a specific range in order to retrieve an image file name.


var images = ["la1.jpg", "la2.jpg", "la3.jpg", "la4.jpg"];
var caption = ["Downtown skyline.", "Hollywood reservoir.", "USC campus.", "Memorial colosseum."];
var num = Math.floor(Math.random()*4);
var imgName = images[num];
var cap = caption[num];
document.write("<img src='" + imgName + "' alt='" + cap + "'><br>" + cap);

Resources