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).
EXAMPLE 9.1
<html>
<head><title>The Array Object</title>
<h2>An Array of Books</h2>
<script type="text/javascript">
1
var book = new Array(6) ; // Create an Array object
2
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";
</script>
</head>
<body bgcolor="lavender">
<big>
<script type="text/javascript">
3
for(var i in book) {
4
document.write("book[" + i + "] "+ book[i] + "<br />");
}
</script>
</big>
</body>
</html>
Search WWH ::




Custom Search