Introduction To Javascript
Arrays

Introduction

By creating arrays, data of a similar type can be grouped together. The following lines of code create an array of names.

var myNames= new Array
myNames[0] = "John"
myNames[1] = "Bill"
myNames[2] = "Bob"

Each element of the array has the same name as the others but a different index (the number in square brackets).

Let me see how that works

The following script uses an array to output the current date to the screen.

var now = new Date()
var days = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var daynum = now.getDate()
document.write("It's " + days[now.getDay()] + " " + daynum + " " + months[now.getMonth()] + ".")

Javascript stores the day of the week as a number between 0 and 6 running from Sunday to Saturday. The months are stored in a similar fashion. An array of words has been created where the index of each day matches the number under which Javascript stores that information.

Exercise 6

Create a script with an array of names. You should have about 5-10 elements in your array. Use a for loop to display all the names on the page.