[英]How do I close the space at the final word so I can insert a period next to it?
It has to do with the iteration length right?它与迭代长度有关吗? How do I iterate it all but the last index?除了最后一个索引,我如何迭代它?
function createSentence(words) { var sentence = ""; for (var i = 0; i < words.length; i++) { sentence += words[i] + ' '; if (i === words.length - 1) return sentence += '.'; } } var result1 = createSentence(['I', 'am', 'worth', 'it']); console.log('should log "I am worth it.":', result1); var result2 = createSentence(['My', 'problems', 'matter']); console.log('should log "My problems matter.":', result2);
Better idea: join by a space, then concatenate a single .
更好的主意:通过空格连接,然后连接单个.
onto the end afterwards:之后到最后:
const createSentence = arr => arr.join(' ') + '.'; var result1 = createSentence(['I', 'am', 'worth', 'it']); console.log('should log "I am worth it.":', result1); var result2 = createSentence(['My', 'problems', 'matter']); console.log('should log "My problems matter.":', result2);
No looping is necessary.不需要循环。 Just join all the array elements with a space and add a .
只需用空格连接所有数组元素并添加.
to the end.到最后。
function createSentence(words) { return words.join(" ") + "."; } console.log('should log "I am worth it.":', createSentence(['I', 'am', 'worth', 'it'])); console.log('should log "My problems matter.":', createSentence(['My', 'problems', 'matter']));
@CertainPerformance's solution is ideal. @CertainPerformance 的解决方案是理想的。
If you want to avoid using join
for educational purposes you could only append a space when i is not at the last position:如果您想避免将join
用于教育目的,则当我不在最后一个 position 时,您只能 append 一个空格:
function createSentence(words) { var sentence = ""; for (var i = 0; i < words.length; i++) { sentence += words[i]; if (i === words.length - 1) { return sentence += '.'; } else { sentence += ' '; // <--- } } } var result1 = createSentence(['I', 'am', 'worth', 'it']); console.log('should log "I am worth it.":', result1); var result2 = createSentence(['My', 'problems', 'matter']); console.log('should log "My problems matter.":', result2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.