Javascript 中出现的逗号呈现 HTML

Commas Appearing in Javascript rendered HTML

我正在用 Javascript 和 Contentful 渲染 HTML。

我的代码:

contentfulClient.getEntries({
   content_type: PRODUCT_CONTENT_TYPE_ID,
   order: '-fields.dateRated'
})
.then(function(entries) {
   container.innerHTML = renderProducts(entries.items)
})

function renderProducts(products) {
   return '<table id="film-table"><tr><th>Name</th><th>Rating</th></tr><tr><td>Check back tomorrow</td><td class="rating-cell"></td></tr>' +
   products.map(renderSingleProduct) +
   '</table>'
}

但是,当我对此进行测试时,每个条目的 table 上方都会出现一个逗号: commas above table.

感谢您的帮助。

这里的问题是 .map 函数 returns 一个数组。因此,当您将 products.map(renderSingleProduct) 添加到现有字符串时,它会将此数组转换为一个字符串,其中包括 , 作为分隔符。

如果您在末尾添加一个 .join('') 调用,一切都应该没问题,因为这会将数组变回带有提供的分隔符的字符串。

function renderProducts(products) {
   return '<table id="film-table"><tr><th>Name</th><th>Rating</th></tr><tr> 
          <td>Check back tomorrow</td><td class="rating-cell"></td></tr>' 
            +
            products.map(renderSingleProduct).join('') +
          '</table>'
          }