使用 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.
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短