【问题标题】:how can I divide strings from array with a comma in js/css?如何在 js/css 中用逗号分隔数组中的字符串?
【发布时间】:2017-11-19 10:16:24
【问题描述】:

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

【问题讨论】:

  • 添加一个 if 看看是不是 alst if is than 不要输出它

标签: javascript css ejs


【解决方案1】:

针对您的特定用例,添加一个三元运算符。 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>

【讨论】:

    【解决方案2】:

    为除最后一个元素之外的所有元素创建一个 for 循环,并在每个主题标签后添加“,”。并在循环之后单独做最后一个标签

    <div class="thumbnail">
            <img src=<%= photo.thumb_url %> >
            <div class="caption">
                <p><% for(var i=0; i<photo.hashtags.length - 1; i++) {%>
                <a href="http://example.com/<%=photo.hashtags[i]%>"><%=photo.hashtags[i] %>, </a>
                <% } %>
                <a href="http://example.com/<%=photo.hashtags[i+1]%>"><%=photo.hashtags[i] %>
                | <a href="<%= photo.photo_url  %>">full resolution</a></p>
            </div>
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多