HTML and CSS Reference
In-Depth Information
EXPLANATION
1
The variable book is assigned a reference to a new Array object containing six el-
ements. You can leave out the size 6 and JavaScript will dynamically build the ar-
ray as you add elements to it.
2
The first element of the book array is assigned the string “War and Peace” . Array
indexes start at zero.
3
The special for loop is used to access each of the elements in the book array where
i is a variable used to represent the index value.
4
Each of the elements of the book array are displayed in the browser (see Figure 9.3).
Figure 9.3 The book array elements and their values.
Creating an Array Literal. The array literal is a quick way to create and populate an
array. To use the literal notation (array), the array is given a name and assigned a list of
elements. The elements are separated by commas and enclosed between a set of square
brackets.
var myarray=["Joe", "Bob", "Ken"]
Once declared, a literal array behaves like a normal array using index values starting
at 0, and so on. Current best-practice tells us that the literal way of creating an array is
preferred to using the new keyword.
Can you see the difference between the following array declarations?
var array1 = new Array(10);
var array2 = [ 10 ];
The first array is specified to be a 10-element array. The second array is initialized
with the value of the first element being the number 10.
 
Search WWH ::




Custom Search