HTML and CSS Reference
In-Depth Information
trick to remember that the indexing starts from zero is to imagine the array all lined up. The first element
will be at the start; the second 1 unit away; the third 2 units away, and so on.
The length of the array is kept in an attribute of the array named length . To access the first component of
the facts array, you use fact[0] ; for the second element, fact[1] , and so on. You will see this in the
coding.
A common way to do something with each element in an array is to use a for loop. (See also the
explanation for setting up the gradient in the walls of the bounding box in Chapter 3.) Suppose you have an
array named prices and your task is to write code to increase each of the prices by 15%. Further, each
price has to increase by a minimum of 1, even if 1 is more than the 15%. You could use the construct in
Table 6-1 to perform this task. As you can see in the Explanation column, the for loop does the same
thing for each component of the array, using the indexing variable i in this example. This example also
shows the use of the Math.max method.
Table 6-1. Increasing Prices in an Array Using a For Loop
Code
Explanation
for(var i=0;i<prices.length;i++) { Do the statements inside the brackets, changing the value of
i , starting at 0 and increasing by 1 (thats what i++ does)
until the value is not less than prices.length , the number
of elements in the array.
prices[i] += Math.max
(prices[i]*.15,1);
Remember to interpret this from the inside out. Compute .15
times the i th element of the array prices . See whats
greater, this value or 1. If it is this value, thats what
Math.max returns. If it is 1 (if 1 is more than
prices[i]*.15 ), use 1. Add this value to the current value
of prices[i] . Thats what += does.
}
Close the for loop
Notice that the code does not state the size of the prices array explicitly. Instead it is represented in the
expression prices.length . This is good because it means that the value of length changes
automatically if and when you add elements to the array. Of course, in our example we know the number to
be 20, but in other situations its better to keep things flexible. This application can be a model for a quiz
involving any number of facts when a fact is two pieces of information.
Our facts array is an array of arrays, which means youll see the following in the code:
facts[i][0] the country name
facts[i][1] the capital city name
facts[i][2] the true/false value indicating this country/capital has been used
These expressions are interpreted as the 0 th element of the i th element of the facts array and so on. I do
refer to the inner arrays as rows, but keep in mind that there are not really any columns. Some
programming languages support multi-dimensional arrays as a primitive data type, but JavaScript only
 
Search WWH ::




Custom Search