Search code examples
javascriptfor-loopinnerhtml

Writing the result of a for-loop to the webpage using innerHTML in Javascript


I am learning Javascript and I am now getting bored of the console, so I would like to "write" to the webpage itself.

I am writing the result of a for loop to the page, I want to print the result, putting a comma after every index, I have managed to accomplish this but there is a comma at the end of the last result, how do I stop the comma after the 9th index? I assume I need to use an index of some sort (i[9]) but I'm not sure how to say stop writing commas.

Here is my code:

var x = document.getElementById("para1");
x.innerHTML = "Result: ";
for(var i = 1; i < 11; i++) {
    result= i + "," + " ";
x.innerHTML += result;
}

One other thing, I am printing "result" in the x variable's innerHTML, is there another way to write variable except in the actual HTML of the page? for instance in the x.innerHTML at the end?

I would greatly appriciate any help!

Thanks


Solution

  • I would use an array and then after the loop has finished, join the array on , and then append to the innerHTML:

    var x = document.getElementById("para1");
    var result = [];
    for(var i = 1; i < 11; i++) {
        result.push(i);
    }
    x.innerHTML = "Result: " + result.join(", ");