使用 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.
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP