使用map()的意外逗号 [英] Unexpected comma using map()
本文介绍了使用map()的意外逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含元素列表的数组:
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'
],
我正在尝试使用模板字符串将此列表附加到HTML元素:
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)
如何避免这种情况?
编辑:已添加代码段
推荐答案
解释
模板文字使用 toString ()
默认情况下,通过 map
将返回的数组与,
连接起来的方法。< br>
为了避免这个问题你可以使用 join('')
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('')
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>
这篇关于使用map()的意外逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文