Clip Art Arrays
Pierce Home
Computer Science 555 Website Development using JavaScript and AJAX - 3 Units
Section:
3179
Instructor:
Brad Gilbert
Pierce Mailbox:
612
Email:
pierce@wavethunder.com
Wednesday Office Hours:
5:00 -   5:40 PM COSC 1507
Wednesday Lab:
5:45 -   7:50 PM COSC 1507
Wednesday Lecture:
7:55 - 10:00 PM MATH 1511
Other classes:
CS-575
arrays
Question:

What is an array?

Answer:

An array is a collection of like objects, for example: Grades, lab scores, favorite web pages...

Question:

How do I declare an array?

Answer:

Old technique for declaring arrays:

    var grades = new Array();

    // array initialized with data
    var students = new Array("Brad", "Bob", "Linda", "Mary");
    

Current technique for declaring arrays:

    var grades = [];

    // array initialized with data
    var students = ["Brad", "Bob", "Linda", "Mary"];
    
Question:

How do I work with arrays?

Answer:

Use the [] operator to access individual elements, one at a time, in an array. For example:

    // Assign "Marge" to the 4th array element (replacing "Mary").
    students[3] = "Marge";
    
    // Assign the first student in the array to the variable currentStudent.
    var currentStudent = students[0];
    // currentStudent === "Brad"
    
Note:

Always start counting from 0, so the first array element is [0], not [1],
and the last element in the students array is [3], not [4].

Question:

How do I know how many elements are in an array?

Answer:

Use the length property. For example:

    var arrSize = students.length;
    // arrSize === 4
    
Important:

The last element of an array is always 1 less than the array length!

    // The below code will not work:
    currentStudent = students[arrSize];
    // currentStudent === undefined

    // This code is OK:
    lastStudent = students[arrSize - 1];
    // lastStudent === "Marge"
    
Question:

Can I add to an array?

Answer:

Yes. For example:

    students[students.length] = "Michael";
    
Question:

What is the value of using an array?

Answer:

Arrays are a very powerful programming tool when combined with loops. Using a variable to access each element, and incrementing that variable for each iteration, you can cycle through the contents of an array of any size with just a few lines of code! For example:

    var idx = 0;
    ...
    currentStudent = students[idx];
    idx++;
    ...
    
Question:

What else can I do with arrays?

Answer:

There are many built-in methods for working with arrays. A reference can be found at:
w3Sschools - array object

Brad Gilbert · Fall 2011
Computer Science · Pierce College · Woodland Hills CA · 818-719-6401