Printing each value of an array on a separate line Javascript

后端 未结 2 1172
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 18:42

I have a program that involves Javascript to allow for interaction with a webpage. It\'s a baseball site so what I am doing is prompting the user to enter a month. The user

相关标签:
2条回答
  • 2021-01-15 19:14

    You can use .join() to combine the array into one string, and separate each entry by <br>:

    document.getElementById("result").innerHTML =
      schedule.join("<br>");
    

    There's no need for the self-closing / in <br>. More important, there's no need for the for loop. That code above will do the whole thing.

    If you want a <br> after the last entry, just add it:

    document.getElementById("result").innerHTML =
      schedule.join("<br>") + "<br>";
    
    0 讨论(0)
  • 2021-01-15 19:15

    While Pointy's answer is correct it does not explain why your code is not working. I'll try and explain:

    The error is in this for loop and how you are using innerHTML.

    for(var i = 0; i < schedule.length; i++)
    {
        document.getElementById("result").innerHTML = schedule[i] + "<br />";
    }
    

    Basically, on each iteration of the loop you are resetting the HTML of the result element instead of appending to it. The following small change is all that would have been needed.

    for(var i = 0; i < schedule.length; i++)
    {
        document.getElementById("result").innerHTML += schedule[i] + "<br />";
    }
    

    However, Pointy's answer is more efficient for sure.

    0 讨论(0)
提交回复
热议问题