d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Javascript Help Please > Very Simple Script
Add Reply New Topic New Poll
Member
Posts: 7,026
Joined: Apr 3 2008
Gold: 1.00
Jan 14 2013 12:28am
Code
<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="Trololo",i=0;
for (i=0;i<10;i++)
 {
 if (i==3)
   {
   break;
   }
 x=x + "The number is " + i + "<br>";
 }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>


Question is, why is the loop output:
TrololoThe number is 0
The number is 1
The number is 2

The way I see it, the input should be:
TrololoThe number is 0
TrololoThe number is 1
TrololoThe number is 2

Thank you for helping me out!

This post was edited by bail6002 on Jan 14 2013 12:29am
Member
Posts: 14,235
Joined: Apr 20 2007
Gold: 15.00
Jan 14 2013 07:07am
you initialize x with the content: Trololo

Code
var x="Trololo"


then later you append only the "The number is ..." part.
if you want to repeat trololo too, you have to add it for each line
instead of
Code
x=x + "The number is " + i + "<br>";

use
Code
x=x + "Trololo The number is " + i + "<br>";
Member
Posts: 7,026
Joined: Apr 3 2008
Gold: 1.00
Jan 14 2013 11:38am
Okay but then I have an other question. Why do we include x? Like what is the purpose of the second x?

Code
x="Trololo The number is " + i + "<br>";


Shouldn't this code do the job?
Member
Posts: 2,478
Joined: Jan 4 2007
Gold: 7,545.00
Jan 14 2013 02:34pm
Quote (bail6002 @ Jan 14 2013 11:38am)
Okay but then I have an other question. Why do we include x? Like what is the purpose of the second x?

Code
x="Trololo The number is " + i + "<br>";


Shouldn't this code do the job?



Because of this line:

Code
document.getElementById("demo").innerHTML=x;


You replace that paragraph with x.
If you don't append to X, you only display the last line of the for loop which would be

Code
"Trololo The number is 2 <br>"


This post was edited by DirtyRasa on Jan 14 2013 02:34pm
Member
Posts: 7,026
Joined: Apr 3 2008
Gold: 1.00
Jan 14 2013 08:15pm
Oh god I get it now lol thanks I was misreading. I don't know why, but in my head this line:
Code
x=x + "The number is " + i + "<br>";

Was actually writing it line by line, instead of this line:
Code
document.getElementById("demo").innerHTML=x;

writing the whole paragraph at once

Thank you for your answers!
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll