HTML and CSS Reference
In-Depth Information
In addition to using the increment or decrement operators, you can multiply or divide the
counter value. The following code prints out a set of numbers that increase by a factor of 2 up
to 100:
for(var i= 1; i<100;i*=2){
document.write(i);
document.write("<br />");
}
The expression piece of the for loop doesn't need to be a hard-coded value, like what has
been shown so far. Instead, you can derive the expression from the length of an object or
another variable, as in this example:
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
for (var i = 0; i < alphabet.length; i++) {
document.write(alphabet[i]);
document.write("<br />");
}
Because a string is just an array of characters, this code can iterate over the string and print
each character to the screen. The length of the string determines how many times the loop
runs.
Using the for…in loop
The for…in loop is a method for iterating over an object's properties. Take the following
example:
var person = { firstName: "Jane", lastName: "Doe", birthDate: "Jan 5, 1925", gender:
"female" };
for (var prop in person) {
document.write(prop);
}
This for loop prints out the name of each property on the custom person object. If you
want the loop to print the property values instead, each property needs to be accessed via
the property indexer of the object, as in this example:
var person = { firstName: "Jane", lastName: "Doe", birthDate: "Jan 5, 1925", gender:
"female" };
for (var prop in person) {
document.write(person[prop]);
}
Using the while loop
The while loop lets you run a code block until some condition evaluates to false . The construct
of the while loop is as follows:
while(< expression >){
< code block >
}
 
Search WWH ::




Custom Search