我有一个函数,它使用条件分隔符连接一个对象数组.
function getSegmentsLabel(segments) { var separator = '-'; var segmentsLabel = ''; var nextSeparator = ''; _.forEach(segments,function(segment) { segmentsLabel += nextSeparator + segment.label; nextSeparator = segment.separatorUsed ? separator : ' '; }); return segmentsLabel; }
用途:
var segments = [ {label: 'First',separatorUsed: true},{label: 'Second',separatorUsed: false},{label: 'Third',{label: 'Forth',separatorUsed: true} ]; getSegmentsLabel(segments); // Result: "First-Second Third-Forth"
解决方法
您可以使用将返回新数组的map()方法,然后使用join()来获取该数组的字符串形式.
var segments = [ {label: 'First',separatorUsed: true} ]; function getSegmentsLabel(segments) { return segments.map(function(e,i) { return e.label + (i != segments.length - 1 ? (e.separatorUsed ? '-' : ' ') : '') }).join('') } console.log(getSegmentsLabel(segments));