Arrays and the Date Object
Rather than printing the default numeric values that the Date object's methods,
getDay() and getMonth() return, the NAMES of the current day of the week and month are printed, resulting in a date string that is understood by people.
The above date string is printed using the following code:
document.write(weekdayNames[day] + ", " + monthNames[month] + " " + date)
You may notice the previously created
day and
month variables surrounded by
array notation. By creating arrays whose element values are weekday and month names, and whose indices correspond with the integers returned by the Date Object's methods, getDay() and getMonth(), we are able to convert a nonsensical date string to a meaningful format.
First we create an array whose element values are weekday names, and an array whose element values are month names:
var weekdayNames = new Array(7)
weekdayNames[0] = "Sunday"
weekdayNames[1] = "Monday"
weekdayNames[2] = "Tuesday"
weekdayNames[3] = "Wednesday"
weekdayNames[4] = "Thursday"
weekdayNames[5] = "Friday"
weekdayNames[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 at this point, reference an array element corresponding to that day or month's name:
document.write(weekdayNames[0])
document.write(monthNames[4])
As you can see, this is not an efficient way to print the current date string to your web page. In order to stay up to date, you'd have to manually change the "weekdayNames" array indices daily, and the "monthNames" array indices monthly.
To create a script that does the work for us, we'll use the following Date() object method variables for the array indices.
Since we know the values of the Date object methods will be returned as integers, we can easily replace the manually inserted numeric indices with the variables storing the returned values.
var now = new Date()
var day = now.getDay()
var month = now.getMonth()
document.write(weekdayNames[day])
document.write(monthNames[month])
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