Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Help with simple javascript coding while loop

    I am in a class for AJAX/Javascript and we had to write an array with a while loop and a for loop this week.

    The while loop supposed to loop through the array.
    The for loop is supposed to reverse the array.

    I have the code working, but I would like the heading to only be iterated once above the loops.

    I am probably missing something pretty basic, but any help would be appreciated.



    Here is the code:

    <script>
    var myClasses=["Flash","AJAX","Advanced Dreamweaver","XML"];
    var i=0;
    var x = myClasses.length - 1;

    while (i <= x)
    {
    document.write("<h3>Spring 2014 Classes:</h3><br>" + myClasses[i] + "<br>");
    i++;
    }

    document.write("<p>");

    for (i=x;i >= 0; i--) {
    document.write("<h3>From the bottom up my spring classes are: </h3>" + myClasses[i] + "<br>");
    }

    document.write("</p>");
    </script>

  • #2
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,130
    Thanks
    38
    Thanked 504 Times in 498 Posts

    Lightbulb

    Put the heading information before the loop and take it out of the loop.
    Leave the myClasses[i] stuff alone.

    For example:
    Code:
    <script>
    var myClasses=["Flash","AJAX","Advanced Dreamweaver","XML"];
    var i=0, x = myClasses.length - 1;
    
    document.write("<h3>Spring 2014 Classes:</h3><br>");
    while (i <= x) { document.write(myClasses[i] + "<br>"); i++; }
    
    document.write("<p>");
    
    document.write("<h3>From the bottom up my spring classes are: </h3>");
    for (i=x;i >= 0; i--) { document.write(myClasses[i] + "<br>"); }
    
    document.write("</p>");
    </script>
    BTW: You should enclose your code betwee [ code] and [ /code] tags (without the spaces)
    to make it easier to view and test. It also retains your formatting.
    Last edited by jmrker; 02-10-2014 at 10:55 PM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •