javascript - 如何在 js/css 中用逗号分隔数组中的字符串?

标签 javascript css ejs

我正在使用 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/

相关文章:

javascript - 有没有办法测试 jqGrid 是否有数据?

css选择器元素

css - SCSS 用一个类扩展另一个类

html - 是否可以右键单击表单元素来打开新页面?

node.js - 在EJS页面上访问mongoDB数据

javascript - 从 HTML 获取 Angular 的未定义值

javascript - CRM 身份验证问题

javascript - AngularJS 作用域问题

javascript - 在 Javascript 中实现 Keybase 的 HMAC-SHA256

javascript - 如何从 ejs 转换为 jade?