![]() | |
![]() |
|
![]() |
The while statement.
while (condition) { do stuff; }
Consider the following...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="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" to 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.)
<< BACK NEXT >> |
![]() |
![]() |
Javascript Reference irt.org/Javascript FAQ Deja Power Search ![]() |
![]() |
Print version available - Get the PageTutor book & CD |
![]() |
![]() |
|
|