If I have an array like ["AAA", "BBB", "CCC"] and what to render to the browser a comma after each one EXCEPT the last one in jquery/JS, how do I do that with the function below? Right now, it adds a comma to all elements in the array that includes the last one, and I don't want it on the last one.
JS
if(designations) {
var newLinks = designations.map(function(agentDesignations){
agentDesignations = agentDesignations.toLowerCase();
return '<a class = "designation-box" data-toggle = "modal" data-target = "#' + agentDesignations + '-modal" data-value = '+ agentDesignations + '>' + agentDesignations + '</a>' + ',\n'});
return newLinks.join("\n");
}
通过使用正则表达式+$
来解决问题
return newLinks.join("\n").replace(/,+$/,'');
remove the ",\\n" from the return in the map, and change the last return to newLinks.join(",\\n\\n")
like this:
if(designations) {
var newLinks = designations.map(function(agentDesignations){
agentDesignations = agentDesignations.toLowerCase();
return '<a class = "designation-box" data-toggle = "modal" data-target = "#' + agentDesignations + '-modal" data-value = '+ agentDesignations + '>' + agentDesignations + '</a>';
});
return newLinks.join(",\n\n") + '\n';
}
there's two "\\n" in the join, because that's what you'd end up with currently
more concisely, I'd code this as follows:
if(designations) {
return designations.map(function(agentDesignations){
agentDesignations = agentDesignations.toLowerCase();
return '<a class = "designation-box" data-toggle = "modal" data-target = "#' + agentDesignations + '-modal" data-value = '+ agentDesignations + '>' + agentDesignations + '</a>';
}).join(",\n\n") + '\n';
}
note: two \\n's vs one \\n's have make no difference on the rendering of the resulting HTML, so the last line can simply be
}).join(",\n") + '\n';
or even
}).join(", "); // note the SPACE, it does make a difference
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.