使用 map()的意外逗号

我有一个包含元素列表的数组,我尝试使用模板字符串将这个列表附加到一个 HTML 元素:

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?

36932 次浏览

解释

template literals use the toString() method which by default joins the returned array by map with a ,.
为了避免这个“问题”,您可以使用 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>

返回一个 array。您可能希望返回一个包含连接在一起的数组元素的 绳子。你可以用 .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>

正如其他人指出的(为了完整起见,我将重复这一点) ,Array.prototype.map返回一个新数组,其中包含在传递给它的函数中被修改的元素。

当您将一个数组连接到一个字符串时(这里正在进行) ,它也会将该数组转换为一个字符串。当数组转换为字符串时,它会自动使用逗号进行连接。

const arr = ['<a>', '<b>'];


console.log(arr + ""); // <a>,<b>

除了使用 .join()显式地传递一个空字符串作为分隔符之外,还可以使用 Array.prototype.reduce替换 .map(),从而将数组减少到一个值。

description.reduce((acc, work) => acc + `<li>${work}</li>`, '')

所以完整的代码应该是这样的:

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.reduce((acc, work) => acc + `<li>${work}</li>`, '')
}
</ul>
</div>
`
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

对于简单的代码,我只是这样使用: ${ description. map ((work) = > <li>${work}</li>) . join (”)}