Results 1 to 3 of 3

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

  1. #1
    Join Date
    Apr 2014

    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++) {
    for (var 
    col 0col 10col++) {
    document.write(" * ");

    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
    Behind you...
    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.
    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:
    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
    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