This example demonstrates how to create an array used with the Date Object Constructor.
Start by creating an array for each day of the week and an array for each month of the year:
var weekDays = new Array(7)
weekDays[0] = "Sunday"
weekDays[1] = "Monday"
weekDays[2] = "Tuesday"
weekDays[3] = "Wednesday"
weekDays[4] = "Thursday"
weekDays[5] = "Friday"
weekDays[6] = "Saturday"
var monthNames = new Array(12)
monthNames[0] = "January"
monthNames[1] = "February"
monthNames[2] = "March"
monthNames[3] = "April"
monthNames[4] = "May"
monthNames[5] = "June"
monthNames[6] = "July"
monthNames[7] = "August"
monthNames[8] = "September"
monthNames[9] = "October"
monthNames[10] = "November"
monthNames[11] = "December"
To write a day or month's name, reference an individual element corresponding to that day's name:
document.write(weekDays[0]) //prints "Sunday"
document.write(monthNames[4]) //prints "May"
As you can see, this is not an efficient way to print date information
to your Web page. In order to stay up to date, you'd have to manually change the
weekDays array elements daily, and the monthNames array elements monthly.
To create a script that does all the work for us, we'll combine arrays with our
Date() object variables.
Since we know the values of the Date object methods stored in our variables will be returned as integers, we
can use those variables as the index, or slot numbers when referencing the arrays:
var now = new Date()
var day = now.getDay()
//returns a value 0-6, depending on which day it is
var month = now.getMonth()
//returns a value 0-11, depending on which month it is
document.write(weekDays[day]) //since "day" represents 0-6, it is used to determine which weekDays element to print
document.write(monthNames[month]) //since "month" represents 0-11, it is used to determine which monthNames element to print
The "getDay()" and "getYear()" methods return values that are already meaningful to us, so there is no need use an array to assign new values to them.
View the Source