Unexpected comma using map()

允我心安 提交于 2019-12-03 05:28:17

问题


I've an array with a list of elements:

  description: [
    'HTML & CSS',
    'Responsive Design Fundamentals',
    'Javascript object-oriented programming',
    'jQuery',
    'Website Performance Optimization',
    'CRP and RAIL',
    'REST API and Ajax',
    'Javascript Design patterns',
    'Bootsrap Framework',
    'Polymer Web Elements'
  ],

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 (see the snippet below)

How can I avoid this?

EDIT: snippet added


回答1:


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>



回答2:


.map() returns an array. You probably want to return a string containing the array elements concatenated together. You can do that with .join(''):

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('') /* added .join('') here */}</ul>
  </div>
  `
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


来源:https://stackoverflow.com/questions/45812160/unexpected-comma-using-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!