while (condition) { do stuff; }
Consider the following...
<html> <head> <title></title> <script type="text/javascript"> function Adder() { number = 1; while (number < 5) { alert(number + " is less than 5"); number = number + 1; } } </script> </head> <body> <a href="javascript:Adder()">Click here</a> </body> </html>
See what's going on here? Study the example until you do.
While we're here, there's a little programming shortcut you might be interested in. It is very common to increment or decrement a number by 1. In the last example we wrote it as...
number = number + 1;
This can also be written as...
number++;
You'll see this a lot in javascript, plus it's fairly common in other programming languages as well.
The same shorthand can also be used for subtraction...
number--;
is the same as
number = number - 1;
Exercise: Alter the example above to prompt the user for both the first and last number. And use the number++ shorthand notation. (When you run this, I wouldn't make your "spread" too large or you'll be clicking alert boxes for an hour.)
Notice I multiplied the prompt box by 1. This is so that all entries are forced into being numbers before we do anything with them. If we left that out, multi-digit numbers such as 12 are sometimes considered strings rather than numbers.
Exercise: Alter your last exercise to check if the second number is larger than the first. If it's not, inform the user and have him try again. (Hint: You'll need to add an if-else statement in there.)
Javascript Tutor |
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Javascript Authoring Guide JavaScript FAQ |
HTML 4.0 Reference Google Groups (Advanced Search) |
![]() |