Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mirko Nobelen
7,507 Pointscan you use a prompt in a For loop in Javascript?
Dear Sir or Madam,
I want to use a prompt in a for loop as part of a test app.
My goal was to have the Hi printed the number of times the user inputted.
I used the code below, however I seem to go into an endless loop. Should I use a Do while/while loop instead or can I also use a For loop, if so what is wrong with my code.
var numberOfHi = prompt ("how many times do you want to say hi");
var nrHi= parseInt(numberOfHi);
var textHi=" ";
var printHi;
for (printHi = 0; printHi = nrHi ; printHi++ ) {
textHi += "<h1>hi</h1>";
}
document.write(textHi);
thanks in advance,
Mirko
3 Answers
miikis
44,957 PointsHey Mirko,
In your original question, as you've observed, your for-loop would never stop. Your solution though, while almost correct, still has an error: you're off by 1. That is to say, when you ask your user for a number, you'll always print "Hi" one too many times. This is because your for-loop is starting at zero and not stopping until it reaches the number the user gave. To fix this you'll want to either start your for-loop at printHi=1 or stop your for-loop at printHi < nrHi.
Your second question is more straight-forward. The reason it's printing the randAttacks function as a string is because you're never actually calling randAttacks. To call a function in JavaScript, you have to put parentheses after the function's name, like this: randAttacks()
Mirko Nobelen
7,507 PointsDear,
I have got it to work however now I want to use a function in my for loop
My goal is to have the program generate a random nr the number of times it was inputted in the prompt
The prompt and the loop run but instead of generating a random nr it prints the code for the function.
var nrAttacks=prompt("How many attacks do you have ?");
var nrAt= parseInt(nrAttacks);
var number=" " ;
/*function randAttacks () {
var randAt = Math.floor (Math.random()*6)+1;
return randAt;
}*/
var attackScore = (randAttacks);
for ( var i = 0; i <= nrAt; i += 1) {
function randAttacks () {
var randAt = Math.floor (Math.random()*6)+1;
return randAt;
}
number = (randAttacks)+ "<br>";
document.write(number);
}
Much oblige,
Mirko
Mirko Nobelen
7,507 PointsHi Mikis,
Super thanks fully understood. I'll get to work and have the start of my first game :-)
Best regards,
Mirko