HTML and CSS Reference
In-Depth Information
Creating Program Loops
• To create a
for
loop, use looping structure
for (
start
;
continue
;
update
) {
commands
}
where
start
is an expression that sets the initial value of a counter variable,
continue
is a Boolean expression that must be
true
for the loop to continue,
update
is an expression that indicates how the value of the counter variable should change
each time through the loop, and
commands
is the JavaScript commands that are run
each time through the loop.
• To create a
while
loop, use the following:
while (
continue
) {
commands
}
• To create a
do
/
while
loop, use the following:
do {
commands
}
while (
continue
);
• To loop through the contents of an array, enter the
for
loop
for (var
i
= 0;
i
<
array
.length;
i
++) {
commands involving
array
[
i
]
}
where
i
is a counter variable representing the indices of the array items and
array
is
the array to be looped through.
With this information, you can create a function that employs arrays and a
for
loop
to create a row displaying the names of the seven days of the week. First, you'll need to
use the following code to create the
dayName
array containing the three-letter abbrevia-
tions for the days:
var dayName = [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”];
Then, you'll loop through the values of the array, displaying each value in a header cell
with the class name
calendar_weekdays
, as follows:
document.write(“<tr>”);
for (var i = 0; i < dayName.length; i++) {
document.write(“<th class='calendar_weekdays'>”
+ dayName[i] + “</th>”);
}
document.write(“</tr>”);
You'll add these commands to a new function named writeDayNames(), and then you'll
apply the function to your monthly calendar.