
本文介绍了使用 map() 的意外逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含元素列表的数组,我正在尝试使用模板字符串将此列表附加到 HTML 元素:
var description = ['HTML &CSS','Javascript 面向对象编程','渐进式网络应用程序 (PWA)','网站性能优化','Webpack 和 Gulp 工作流程','全栈 React.js','网络组件','响应式网页设计','草图设计','GraphQL 和中继']$('body').append(`<div class="描述"><ul>${描述.地图(功能(工作){返回 `<li>${work}</li>`})}
`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
结果我在每个列表元素之间得到了一个意外的逗号.(当您运行上面的代码片段时,您可以看到这一点.)
我怎样才能避免这种情况?
解决方案
说明
模板文字 使用 toString()
方法默认通过 map
将返回的数组与 ,
连接起来.
为了避免这个问题",你可以使用 join('')
代码
var description = ['HTML &CSS','Javascript 面向对象编程','渐进式网络应用程序 (PWA)','网站性能优化','Webpack 和 Gulp 工作流程','全栈 React.js','网络组件','响应式网页设计','草图设计','GraphQL 和中继']$('body').append(`<div class="描述"><ul>${描述.地图(功能(工作){返回 `<li>${work}</li>`}).加入('')}
`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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?
解决方案
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>
这篇关于使用 map() 的意外逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!