Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected comma using map()

I've an array with a list of elements and I'm trying to append this list to an HTML element using template strings:

var description = [   'HTML & CSS',   'Javascript object-oriented programming',   'Progressive Web apps (PWAs)',   'Website Performance Optimization',   'Webpack and Gulp workflows',   'Fullstack React.js',   'Web Components',   'Responsive web design',   'Sketch design',   'GraphQL and Relay' ]  $('body').append(   `   <div class="description">     <ul>       ${description.map(         function(work) {           return `<li>${work}</li>`         }       )}</ul>   </div>   ` )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As a result I get an unexpected comma between each list element. (You can see this when you run the code snippet above.)

How can I avoid this?

like image 220
Lc0rE Avatar asked Aug 22 '17 08:08

Lc0rE


1 Answers

Explanation

template literals use the toString() method which by default joins the returned array by map with a ,.
To avoid this "problem" you can use join('')

Code

var description = [    'HTML & CSS',    'Javascript object-oriented programming',    'Progressive Web apps (PWAs)',    'Website Performance Optimization',    'Webpack and Gulp workflows',    'Fullstack React.js',    'Web Components',    'Responsive web design',    'Sketch design',    'GraphQL and Relay'  ]    $('body').append(    `    <div class="description">      <ul>       ${          description.map(function(work) {            return `<li>${work}</li>`          }).join('')        }      </ul>    </div>    `  )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 162
Roman Avatar answered Oct 15 '22 05:10

Roman