The for statement is a very useful tool. Here is an example...
<html> <head> <title></title> <script type="text/javascript"> function boxPopper() { for (var x = 0; x < 5; x++) { alert(x); } } </script> </head> <body> <a href="javascript:boxPopper()">Click here</a> </body> </html>
Here's what's happening in that for statement...
The loop stops when x is no longer less than 5. (You might be thinking... hey, the loop stopped after 4! To which I ask you... is 5 less than 5? If you say yes, keep thinking about it until you say no ;-)
Exercise: Using the for statement, come up with a script that calculates the square root of each integer from 0 to 20, rounds each to one decimal point and displays them in an alert box like so...
The square root of 0 is 0 The square root of 1 is 1 The square root of 2 is 1.4 etc...
Hint: you can specify a line break in an alert box with an escaped n (n for newline) - \n
alert("Hand\nhand\nfingers\nthumb"); - try it
Again, it's a tough one. Hey, if they were easy you wouldn't learn anything, right?
Exercise: Make a slight alteration to that last exercise and have it round to two decimal places.
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) |
![]() |