JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

guram dgebuadze
guram dgebuadze
Front End Web Development Techdegree Student 4,121 Points

Arrays-for loop, listHTML.

the code written is too complicated will this be right choice to write this way listHTML = '<ol>'; for( var i = 0; i < playList.length; i++) { listHTML += '<li>' + playList[i] + '</li>'; } listHTML += '</ol>'; document.write(listHTML);

Code is less and easier to guess.

2 Answers

Dmitry Fedin
Dmitry Fedin
7,650 Points

Say up we have the following HTML markup:

...
<body>
</body>
...

To create playlist which consists of <ol> and <li> elements we need to write the following JS code:

var songs = [
'Song 1',
'Song 2',
'Song 3'
];

var ol = document.createElement('ol');

for (var i = 0; i < songs.length; i++) {
    var li = document.createElement('li');
    li.innerHTML = songs[i];
    ol.appendChild(li);
}

document.body.appendChild(ol);

Also there is a way with using ES6 features:

const songs = [
'Song 1',
'Song 2',
'Song 3'
];

const ol = document.createElement('ol');

songs.forEach((song) => {
    const li = document.createElement('li');
    li.innerHTML = song;
    ol.appendChild(li);
})

document.body.appendChild(ol);

Both methods give you this result:

...
<body>
    <ol>
        <li>Song 1</li>
        <li>Song 2</li>
        <li>Song 3</li>
    </ol>
</body>
...
guram dgebuadze
guram dgebuadze
Front End Web Development Techdegree Student 4,121 Points

thank you, for your help. But I don't know yet these things, I meant only about function-array - for loop use.