|
Departments Info Home Page Articles Software GoodiesExplanations How do they do that? The Web in FocusResources Web Site Stuff Tech Books E-Books Tech Toys Web Hosting LinksWomen Opinion Tech Women Women's StudiesTech News Computer Security Databases Java Linux MP3 PC Software Robotics Site Owner Tech Latest Web Development XMLSpread the Word Newsletter
Recommend this Page
Site Info Legal Disclaimer
Privacy
Contact
Lighter Side Crazy for Life crazy for romance Crazy for Kitties Crazy for Dogs Crazy for CowsCopyright 2000-2001, hertechnology.com |
Once More, with Feeling! JavaScript loop syntax Unfortunately, we can't just say "repeat this 6 times" in a program like it's written above. Instead, we need to use the specific format, in this case, what JavaScript is expecting. There are different types of loops; we'll be using the very handy "for loop". for loops have a particular syntax that follows this pattern:
for (i=1; i<=6; i++) { What's all that stuff mean?
Some other examples: Loop 10 times: for (i=1; i<=10; i++) We will fill in what to do to pick our lottery numbers next. We're going to use some JavaScript math routines to do this. Math.random chooses a random floating point number (a number with a decimal place in it like 25.87). But lottery tickets are numbers without decimals, so we'll use Math.floor to give us just the number with the decimal part cut off (25). We'll pick numbers from 1 to 49, like so: number = (Math.floor(Math.random()*48)) + 1; What this math-y looking stuff does is pick a random floating point number between 0 and 48, remove the fractional part and add 1 so we end up with a number from 1 to 49. Finally, we want to print it to the screen, so we'll use document.writeln(number + "<br>"); The fourth program
<html> The program as it stands has one flaw -- nothing prevents it from picking the same number more than once. We can fix that, but it requires some programming beyond the basics we're covering here. But in any case, give it a try. If you reload or refresh the page, you will get a different list of numbers. This might be more than you wanted to know about programming. But if nothing else, you can take away the concept that programming languages (most of them) have the notion of looping -- doing basically the same thing multiple times. |
|