www.webdeveloper.com
Results 1 to 3 of 3

Thread: Get document.write to add text after each "for" loop

  1. #1
    Join Date
    Apr 2014
    Posts
    44

    Get document.write to add text after each "for" loop

    Okay guys, I have this assignment for a beginners Javascript class and I have one that I can't quite figure out. If someone could give me a hand, that'd be greatly appreciated.

    Here's my code:
    PHP Code:
    for(var row 0row 5row++) {
    document.write("<p>");
    for (var 
    col 0col 10col++) {
    document.write(" * ");
    }
    document.writeln("</p>");

    Simple, right? Now, how do I alter this so that the asterisk prints only 1 on the first line, 2 times on the second, 3 times on the third, and so on. I thought about using an Array and then starting it at 1 and add to it on each loop, but I can't figure out how to make the Array number increase (can't use "++" I don't think...). Any suggestions?

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    865
    There are a couple ways you could do this. An array (like you mentioned) is plausible, but frankly the same effect could be given by simply using a string.
    Code:
    var $rows = 5;
    var $cols = "";
    for(var $a = 0; $a < $rows; $a++) {
    	$cols += "&nbsp;*&nbsp;";
    	document.write($cols+"<br />");
    }
    As a side note, you could wrap the $cols variable in <p> tags rather than use a line-break, it's really up to your preference.

    While that's probably the simplest way I can think of at the moment, you could probably come up with variations or completely different versions if you'd like. I'd also like to address your issue with increasing the array number. Typically I like to use the .length property to add new items to an array. However you can also use the push() method to essentially do the same thing. Something like:
    Code:
    var $myArray = [];
    $myArray[$myArray.length] = "This is a new item added to the end of an array"; // .length property
    $myArray.push("This is another new item added to the end of an array"); // .push() method
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  3. #3
    Join Date
    Apr 2014
    Posts
    44
    Thanks! That worked great!

    I'll try out the .length and push() methods sometime too. Thanks for those as well.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles