You are looping over all the items in the array with a for loop:
for (var i = 0; i < joelsarray.length; i++) {
Everytime you loop, the variable i
will be incremented: from 0 to 1 to 2..etc.
You can access the values in the array by index using the i
from the iteration: joelsarray[i]
. So joelsarray[2]
would give you joel
.
Before any looping has been done, you could assign the string using =
to the element using:
document.getElementById("demo").innerHTML = "The elements of my array are <br>";
When the looping starts, you want to append using +=
the values to the string you already have added. If you would set the data during the looping using =
, you would overwrite the data constantly after every loop.
You get this result "the elements of my array are true", because true
is the last element in the array and would get written as last losing all the previous values.
You could add +=
to add the inner html
var joelsarray = [1, 2, "joel", "carissa", true];
document.getElementById("demo").innerHTML = "The elements of my array are <br>";
for (var i = 0; i < joelsarray.length; i++) {
document.getElementById("demo").innerHTML += joelsarray[i] + "</br>";
}
<h1>Hello</h1>
<p id="demo">Hello World.Hello World.</p>