This is my html file :
function showMovies(){
const movies = [
{title: 'a nice movie', year: 2020, rating: 4.5},
{title: 'another nice movie', year: 2021, rating: 4.8},
{title: 'just another movie', year: 2022, rating: 4.2}
];
let html ="";
html = movies.map(function(m) {
return "<li>" + m.title + '-' + m.year + "-" + m.rating + "</li>";
});
html = "<ul>" + html + "</ul>";
document.getElementById('list').innerHTML = html;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body onload="showMovies()">
<h2>List of movies</h2>
<div id="list"></div>
<script src="movies.js"></script>
</body>
</html>
When I preview the page, I have extra commas like in the image below :
Is this an expected outcome with map function? Should I chain some joining/splitting fucntions to get rid of the extra commas?
3
Answers
When you do this:
html
was an array, but you’re treating it as a string. In doing so, JavaScript is representing it as a set of comma-separated values.Instead of implicitly converting the array to a string, you can explicitly join it to a string:
Instead of using
.map()
like that. You could create a function that builds your<ul>
, just useforEach
and concatenate each item as a<li>
then close the</ul>
tag when finished and return the HTMLSometimes, especially in loops, it’s actually easier to create the elements programmatically, like this: