Loops in JavaScript
The for loop
for (var = 1; var < 10; var++) { ... }
The while loop
while (total < 10) {
n++;
total += values[n];
}
do {
n++;
total += values[n];
} while (total < 10);
An infinite loop
while (true) { ... }
Breaking out of a loop
while (true) {
n++;
if (values[n] == 1) break;
}
Continuing a loop
for (i = 1; i < 21; i++) {
if (score[i] == 0) continue;
document.write ("Student number ", i, " Score : ", score[i], "\n");
}
The for ... in loop
for (i in navigator) {
document.write ("property: " + i);
document.write (" value: " + navigator[i]);
}
Arrays & loops
names = new Array();
i = 0;
do {
next = window.prompt ("Enter the Next Name");
if (next > " ") names[i] = next;
i = i + 1;
} while (next > " ");
Generating HTML dynamically
document.write ("<OL>");
for (i in names) {
document.write ("<LI>" + names[i] + "<BR>");
}
document.write ("<OL>");
Generating HTML dynamically (Prompt for names and display them)
...
names = new Array();
i = 0;
do {
next = window.prompt ("Enter the Next Name");
if (next > " " && next != "undefined") names[i] = next;
i = i + 1;
} while (next > " " && next != "undefined");
document.write ("<H3>" + (names.length) + " names entered.</H3>");
document.write ("<OL>");
for (i in names) {
document.write ("<LI>" + names[i] + "<BR>");
}
document.write ("</OL>");
...
Run the Script above.