我正在使用 ejs
模板引擎在我的页面上填充数据。
我的 json 文件包含以下字段:
var PhotosSchema = new Schema({
photo_url: {type: String},
thumb_url: {type: String},
hashtags: {type: [String]}
});
到目前为止,我有以下 html 代码:
<div class="thumbnail">
<img src=<%= photo.thumb_url %> >
<div class="caption">
<p><% for(var i=0; i<photo.hashtags.length; i++) {%>
<a href="http://example.com/<%=photo.hashtags[i]%>"><%=photo.hashtags[i] %></a>
<% } %>
| <a href="<%= photo.photo_url %>">full resolution</a></p>
</div>
</div>
它在照片下方显示主题标签,但它们没有用逗号分隔。例如它看起来像这样:
one two three
如何修改我的代码,使其以 ,
符号分隔主题标签,但不将此字符添加到末尾,例如:
one, two, three
这个不正确:
one, two, three,
最佳答案
对于您的特定用例,添加一个三元运算符。 i != photo.hashtags.length - 1 ? ",": ""
<div class="thumbnail">
<img src=<%= photo.thumb_url %> >
<div class="caption">
<p><% for(var i=0; i<photo.hashtags.length; i++) {%>
<a href="http://example.com/<%=photo.hashtags[i]%>">
<%=photo.hashtags[i] %> <%= i != photo.hashtags.length - 1 ? "," : "" %>
</a>
<% } %>
| <a href="<%= photo.photo_url %>">full resolution</a></p>
</div>
</div>
关于javascript - 如何在 js/css 中用逗号分隔数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47372473/