使用 JavaScript 构建基于单词和标点数组的句子
问题
我们需要编写一个JavaScript函数,它接受一组单词和标点符号。我们的函数应该连接数组元素以根据以下规则构造一个句子-
单词之间必须始终有一个空格;
左边的逗号和单词之间不能有空格;
句末必须始终只有一个句号。
示例
以下是代码-
const arr = ['hey', ',', 'and', ',', 'you'];
const buildSentence = (arr = []) => {
let res = '';
for(let i = 0; i < arr.length; i++){
const el = arr[i];
const next = arr[i + 1];
if(next === ','){
res += el;
}else{
if(!next){
res += `${el}.`;
}else{
res += `${el} `;
}
}
}
return res;
};
console.log(buildSentence(arr));输出结果hey, and, you.