Ich benutze ejs
Template-Engine zum Auffüllen von Daten auf meiner Seite.
Meine JSON-Datei enthält die folgenden Felder:
var PhotosSchema = new Schema({
photo_url: {type: String},
thumb_url: {type: String},
hashtags: {type: [String]}
});
Ich habe den folgenden HTML-Code bisher:
<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>
und es zeigt Hashtags unter dem Foto, aber sie werden nicht mit einem Komma geteilt. Zum Beispiel sieht es so aus:
one two three
Wie kann ich meinen Code so ändern, dass er Hashtags teilt? ,
Zeichen, fügt dieses Zeichen jedoch nicht am Ende hinzu, zum Beispiel:
one, two, three
Dieser wäre nicht korrekt:
one, two, three,
Antworten:
1 für die Antwort № 1Fügen Sie für Ihren speziellen Anwendungsfall einen ternären Operator hinzu. 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>
0 für die Antwort № 2
Erstellen Sie eine for-Schleife für alle außer dem letzten Element und fügen Sie nach jedem Hashtag "," hinzu. Und mache den letzten Hashtag separat nach der Schleife
<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>