Java Reference
In-Depth Information
the for . . . in loop
This loop enables you to loop through each element in the array without having to know how many
elements the array actually contains. In plain English, what this loop says is “For each element in
the array, execute some code.” Rather than having to work out the index number of each element,
the for . . . in loop does it for you and automatically moves to the next index with each iteration
(loop through).
Its syntax for use with arrays is:
for (index in arrayName) {
//some code
}
In this code extract, index is a variable you declare prior to the loop, which will automatically be
populated with the next index value in the array. arrayName is the name of the variable holding the
array you want to loop through.
Let's look at an example to make things clearer. You define an array and initialize it with three
values:
var myArray = ["Paul","Paula","Pauline"];
To access each element using a conventional for loop, you'd write this:
for (var loopCounter = 0; loopCounter < 3; loopCounter++) {
document.write(myArray[loopCounter]);
}
To do exactly the same thing with the for . . . in loop, you write this:
for (var elementIndex in myArray) {
document.write(myArray[elementIndex]);
}
As you can see, the code in the second example is a little clearer, as well as shorter. Both methods
work equally well and will iterate three times. However, if you increase the size of the array, for
example, by adding the element myArray[3] = "Philip" , the first method will still loop only
through the first three elements in the array, whereas the second method will loop through all
four elements.
the while loop
Whereas the for loop is used for looping a certain number of times, the while loop enables you
to test a condition and keep on looping while it's true. The for loop is useful when you know how
many times you need to loop; for example, when you are looping through an array that you know
has a certain number of elements. The while loop is more useful when you don't know how many
times you'll need to loop. For example, if you are looping through an array of temperature values
and want to continue looping when the temperature value contained in the array element is less than
100 , you will need to use the while statement.
 
Search WWH ::




Custom Search