HTML and CSS Reference
In-Depth Information
A final way to create an array is with an array literal , in which the array values are
entered in a bracketed list. The expression to create an array literal is
var array = [ values ];
where values is once again a comma-separated list of item values. The following com-
mand uses the array literal form to store an array of month names:
var monthName = [“January”, “February”, “March”, “April”, “May”,
“June”, “July”, “August”, “September”, “October”, “November”,
“December”];
If you know the contents of your array, it's usually quicker and easier to set up your array
using the array literal notation.
Note that all array values do not need to be the same data type. You can mix numeric
values, text strings, and other data types within a single array, as demonstrated by the
following statement:
To create an empty array
literal, leave the brackets
blank as in the command
var x = [];
var x = [“April”, 3.14, true, null];
Creating and Populating Arrays
• To create an array, use the object constructor
var array = new Array( length );
where array is the name of the array and length is the number of items in the array.
The optional length parameter sets the array to a specified size; if omitted, the array
expands as new items are added to it.
• To set a value of an item within an array, use the command
array [ i ] = value ;
where i is the index of the array item and value is the value assigned to the item.
• To create and populate an array within a single command, use
var array = new Array( values );
where values is a comma-separated list of values.
• To create an array using the array literal format, use the following statement:
var array = [ values ];
Now that you've seen how to create and populate an array, you'll create an array of
month names to use in your calendar application. You'll insert the array in a function
named writeCalTitle() whose purpose is to write the header row of the calendar table.
The function has a single parameter named calendarDay that stores a date object con-
taining the date to be highlighted in the calendar. The initial code for the writeCalTitle()
function employs an array literal as follows:
function writeCalTitle(calendarDay) {
var monthName = [“January”, February”, “March”,
“April”, “May”, “June”, “July”, “August”, “September”,
“October”, “November”, “December”];
}
You'll add this function to the calendar.js file now.
Search WWH ::




Custom Search