How to add separator to each item in for loop expect last one
In the loop below, how can I remove the comma from the latt key in the loop?
var resu开发者_C百科lt = 'These are the results: ';
jQuery.each(item['keyterms']['terms'],function(i,kw){
for (key in keywords){
sep = ',';
if (keywords[key] > 5) result += '<span>' + key + sep + '</span>';
}}
Instead of inserting coma inside loop you can use standard javascript function JOIN
var results = Array();
for (key in keywords){
if (keywords[key] > 5) results.push('<span>' + key + '</span>');
}
var message = 'These are the results: ' + results.join(',');
Simple - instead of putting the separator after the key, put it before, and skip the first element (it's much easier to know when the element is first, than when it's last):
var first = true;
var result = '';
for (key in keys) {
var sep = first ? '' : ', ';
result += sep + key;
first = false;
}
note that for joining strings in JS the arrays join(separator) method is faster than the + operator. So I recommend Nazariy's solution. with a small change:
var result = Array();
for (key in keywords){
if (keywords[key] > 5) result.push(['<span>', key, sep, '</span>'].join(''));
}}
result = result.join(',');
If you're just concerned about how to remove the last separator then this should work:
jQuery.each(item['keyterms']['terms'],function(i,kw){
for (key in keywords){
sep = ',';
if (keywords[key] > 5) result += '<span>' + key + sep + '</span>';
}}
result = result.substring(0, result.length - (sep+"</span>").length) + "</span>");
Otherwise, Nazariy's join solution is a better way to create the whole string.
Why do you even add it?
var result = 'These are the results: ';
jQuery.each(item['keyterms']['terms'],function(i,kw){
var sep = '';
for (key in keywords){
if (keywords[key] > 5) result += '<span>' + sep + key + '</span>';
sep = ',';
}}
精彩评论