HTML and CSS Reference
In-Depth Information
EXAMPLE
9.4
<html>
<head><title>The Array Object</title></head>
<body>
<h2>An Array of Colored Strings</h2>
<script type="text/javascript">
1
var colors = new Array("red", "green", "blue", "purple"
);
2
for(var i in colors){
3
document.write("<font color='"+colors[i]+"'>");
4
document.write("colors[" + i + "] = "+ colors[i]
+ "<br />");
}
</script>
</body>
</html>
EXPLANATION
1
A new array called
colors
is created and assigned four colors.
2
The special
for
loop iterates through each element of the colors array, using
i
as
the index into the array.
3
The color of the font is assigned the value of the array element.
4
The value of each element of the colors array is displayed. The color of the font
matches the value (see Figure 9.6). Make sure the background color is not the
same color as the font or you won't be able to see the font.
Figure 9.6
Each string is a different font color: Output from Example 9.4.
The
Array
object only has three properties,
constructor
,
length
, and
prototype
(see Table
9.1). In Chapter 8, we talked about the
constructor
property and the
prototype
property.
The value of the
constructor
property is the name of the constructor function that created
the object. The
prototype
property allows you to customize objects. All objects have this
property, which allows you to add new properties and methods.