/    Sign up×
Community /Pin to ProfileBookmark

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:

[code=php]
for(var row = 0; row < 5; row++) {
document.write(“<p>”);
for (var col = 0; col < 10; col++) {
document.write(” * “);
}
document.writeln(“</p>”);
}[/code]

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?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Sup3rkirbyApr 02.2014 — 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 />");
}
[/CODE]

As a side note, you could wrap the [B]$cols[/B] variable in [B]<p>[/B] 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 [B].length[/B] property to add new items to an array. However you can also use the [B]push()[/B] 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
[/CODE]
Copy linkTweet thisAlerts:
@mrjaneauthorApr 02.2014 — Thanks! That worked great!

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

Success!

Help @mrjane spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...