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
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 = "Sunday"
weekdayNames = "Monday"
weekdayNames = "Tuesday"
weekdayNames = "Wednesday"
weekdayNames = "Thursday"
weekdayNames = "Friday"
weekdayNames = "Saturday"
var monthNames = new Array(12)
monthNames = "January"
monthNames = "February"
monthNames = "March"
monthNames = "April"
monthNames = "May"
monthNames = "June"
monthNames = "July"
monthNames = "August"
monthNames = "September"
monthNames = "October"
monthNames = "November"
monthNames = "December"
To write a day or month's name at this point, reference an array element corresponding to that day or month's name:
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()
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