SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Why are these loop results inconsistent?

    I tried rewriting the same loop for both a for loop and a while loop. The for loop will print my lines to the screen, but the while loop does not. Why would they not work the same? What would I need to do to the while loop to make it have the same behavior as the for loop?

    Code JavaScript:
    var write_this = '\n';
    var i = 0;
    while (i < 3) {
       write_this += 'Does not print to console three times.\n';
       i++;
    }

    Code JavaScript:
    var write_this = '\n';
    for (i = 0; i < 3; i++) {
          write_this += 'Prints to console three times.\n';
    }

  2. #2
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    298
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    var write_this = '\n';
    var i = 0;
    while (i < 3) {
       write_this += 'Does not print to console three times.\n';
       i++;
    }
    console.log (write_this);
    Works fine for me. Maybe it's something else in your script?

    RLM

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm using these with the Firebug console. Could it be a Firebug thing?

  4. #4
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    298
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, likewise using firebug. I'd check the rest of your script, even your script tags.

    RLM

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, there is no actual script. I'm just playing with the different loops. I typed the first loop into Firebug and ran it exactly as I listed it above, and the Firebug console just printed this:

    >>> var write_this = '\n'; var i = 0; while (i < 3) ... not print to console three times.\n'; i++; }
    2


    (Not sure where the "2" is coming from)

    Then I clear the while loop and run the for loop all by itself and Firebug gives me:

    >>> var write_this = '\n'; for (i = 0; i < 3; i++) {...te_this += 'Prints to console three times.\n'; }
    "
    Prints to console three times.
    Prints to console three times.
    Prints to console three times.
    "


    What I'm trying to figure out is why the while loop won't print the 3 lines like the for loop does. I'm guessing it must be printing them out somewhere if it's working for you, but I wonder why my Firebug is acting differently?


Bookmarks

Posting Permissions

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