Lab 5—Your First JavaScripts

Part 2—Build an Array


An array is a collection of numbered items. We'll discuss arrays in more depth in lecture next week.

  1. Open lab05.html in NotePad++.
  2. Save the file as arrays.html.
  3. Change the title of your page to "Array Script by " and your name; for example, "Array Script by Joy."
  4. In the <head> after the <title>, add start and end script tags.
  5. Between the script tags, set up the Harry Potter books as an array, using the syntax and titles in the sidebar. The first two are shown here:.
    var books = new Array("Harry Potter and the Philosopher's Stone","Harry Potter and the Chamber of Secrets");
    Now add the rest of the titles before the closing ).

    Note: Each title needs quotes around it because it's a string. Put commas between titles, or values, in the array.

  6. In the <body>,
    1. Add a heading, "Books".
    2. Add script tags for a body script.
    3. Between the body script tags, set up this script to print the book titles to the page:

      document.write('<ol><li>'+books[0]+'</li><li>'
      +books[1]+'</li><li>'+books[2]+'</li><li>'+books[3]+
      '</li><li>'+books[4]+'</li><li>'+books[5]+
      '</li><li>'+books[6]+'</li></ol>');


  7. Save arrays.html again.
  8. In Firefox, open arrays.html. Do all seven books print to the screen? If not, use the Firefox Error Console to find and fix and errors.

 

Learn how to write the list of books with a for loop....

 

previous page   next page

 

Syntax for Setting Up New Arrays

var arrayName = new Array('value1','value2','value3');

Note the quotes enclosing each item, the commas between titles, and that the last item has no comma following it.

Harry Potter Books

  1. Harry Potter and the Philosopher's Stone
  2. Harry Potter and the Chamber of Secrets
  3. Harry Potter and the Prisoner of Azkaban
  4. Harry Potter and the Goblet of Fire
  5. Harry Potter and the Order of the Phoenix
  6. Harry Potter and the Half-Blood Prince
  7. Harry Potter and the Deathly Hallows

Elements in an Array

Array elements always start at 0. The seven Harry Potter books in the books array are numbered from 0–6:

  1. Harry Potter and the Philosopher's Stone
  2. Harry Potter and the Chamber of Secrets
  3. Harry Potter and the Prisoner of Azkaban
  4. Harry Potter and the Goblet of Fire
  5. Harry Potter and the Order of the Phoenix
  6. Harry Potter and the Half-Blood Prince
  7. Harry Potter and the Deathly Hallows

document.write()

document.write() is a built-in method in JavaScript. It "prints" to the document, or Web page.