HTML and CSS Reference
In-Depth Information
The values can be of any data type or combination of types. Although you can specify
the size of the array when declaring it, it is not required. JavaScript allocates memory as
needed to allow the array to shrink and grow on demand. To populate the array, each
element is assigned a value. Each element is indexed by either a number or string. If the
array index is a number, it starts with 0. JavaScript doesn't care what you store in the
array. Any combination of types, such as numbers, strings, Booleans, and so forth, are
acceptable. Example 9.1 creates a new Array object called book and assigns strings to
each of its elements.
Another popular way to declare an array is with the literal notation. This is a quick
and easy way to declare and populate an array in one step:
var friends = [ "John", "Jane", "Niveeta", "Su" ];
Using the new Constructor. To create an Array object, call the Array() constructor
with the new keyword and optionally pass information to the constructor if you know
the size and/or what elements you want to assign to the array. When a size is supplied
but not values, the empty elements will be assigned undefined . JavaScript provides a
number of methods to manipulate the array (these are listed in the “Array Methods” on
page 227).
<head><title>The Array Object</title>
<h2>An Array of Books</h2>
<script type="text/javascript">
var book = new Array(6) ; // Create an Array object
book[0] = "War and Peace"; // Assign values to its elements
book[1] = "Huckleberry Finn";
book[2] = "The Return of the Native";
book[3] = "A Christmas Carol";
book[4] = "The Yearling";
book[5] = "Exodus";
<body bgcolor="lavender">
<script type="text/javascript">
for(var i in book) {
document.write("book[" + i + "] "+ book[i] + "<br />");
Search WWH ::

Custom Search