如果我有一个数组,如[" AAA"," BBB"," CCC"]以及在每个EXCEPT之后向浏览器呈现逗号的内容jquery / JS中的最后一个,我怎么用下面的函数做到这一点?现在,它为数组中包含最后一个元素的所有元素添加了逗号,并且我不想在最后一个元素上使用它。
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");
}
答案 0 :(得分:0)
使用正则表达式+$
return newLinks.join("\n").replace(/,+$/,'');
答案 1 :(得分:0)
从地图中的返回中删除“,\ n”,并将最后一次返回更改为newLinks.join(",\n\n")
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';
}
联盟中有两个“\ n”,因为这就是你最终的目标
更简洁,我将其编码如下:
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';
}
注意:两个\ n和一个\ n \ n对生成的HTML的渲染没有任何区别,所以最后一行可以简单地
}).join(",\n") + '\n';
甚至
}).join(", "); // note the SPACE, it does make a difference