I am trying to add line breaks in a for-loop in a stand alone .js file, linked to a HTML.
I have my variable set to an array with 3 objects inside. I want my for-loop to run once, then print the values on a new line in my browser using document.write. However, when I run my loop, all 3 objects are displayed in 1 single line instead of an actual list. I have tried using <br>
& \n
to add line breaks, but when I do, the text in my browser disappears. What am I doing wrong here?
let pokemonList = [{
name: 'caterpie ',
height: 0.3,
types: ['bug', 'electric']
},
{
name: 'sandslash ',
height: 1,
type: ['ground']
},
{
name: 'meowth ',
height: 0.4,
type: ['normal']
},
]
for (let i = 0; i < pokemonList.length; i++) {
document.write(pokemonList[i].name + 'height: ' + pokemonList[i].height);
}
You could use template literals
to make it easier to read.
let pokemonList = [{
name: 'caterpie ',
height: 0.3,
types: ['bug', 'electric']
},
{
name: 'sandslash ',
height: 1,
type: ['ground']
},
{
name: 'meowth ',
height: 0.4,
type: ['normal']
},
]
for (let i = 0; i < pokemonList.length; i++) {
document.write(`${pokemonList[i].name} height: ${pokemonList[i].height}<br/>`);
}