Log in

View Full Version : Append string to the end of string via a loop



l_kris06
06-24-2009, 02:53 PM
Hi all,

I am trying to append a string with some more string data. This sounds simple, but I am unable to do it.

This is what i am trying to do:


<script>
for(var i = 0; i<10;i++){
appendString += "This is number "+i+"<BR>";
}

document.write(appendString);
</script>

I want my output to be,
This is number 1
This is number 2
This is number 3
.
.
.
However this doesnt work. Can somebody help me understand why ?

l_kris06
06-24-2009, 02:59 PM
OK, I fixed it, looks like the variable needs to be initialized before being using it in the loop.

fixed code:


<script>
appendString='';
for(var i = 0; i<10;i++){
appendString += "This is number "+i+"<BR>";
}

document.write(appendString);
</script>