AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Resources - FAQ - Javascript Q10

FAQ - Javascript Q10



Q10:How do I print numbers 1 - 10 using javascript?

A:Sequences are made using for loops. The structure looks like this

<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
for (var i = 0; i < 10; i++){
document.write(i + " | ");
}
// -->
</SCRIPT>

var i = 0; : sets the variable i to 0
i < 10; : means keep going while i is less than 10
i++ : increase i by 1 each loop
document.write(i + " | "); : this writes the variable i to the page - + " | " is for formatting

The output is below

So that explains it - except it displays 0-9 - you wanted 1 - 10
OK change var i = 0; i < 10; to var i = 1; i <= 10;

Now we get the desired result

Here are some other examples

even numbers between 0 and 10
Change var i = 0; i <= 10; i++ to var i = 2; i <= 10; i+=2

odd numbers between 1 and 10
Change var i = 0; i <= 10; i++ to var i = 1; i <= 10; i+=2

To break out of a loop once a certain number is reached use this

Heres the code

<SCRIPT LANGUAGE="JavaScript" type="text/javascript"> 
<!-- 
for (var i = 1; i <= 10; i+=1) { 
document.write(i + " | "); 
    if(i == 5){ 
    document.write(" stopped "); 
    break; 
    } 

// --> 
</SCRIPT>

These were just a few examples of how you can use a for loop




back to faq




Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]