我们需要编写一个JavaScript函数,该函数接受包含英文字母的字符串。该函数应返回一个对象,该对象包含字符串中元音和辅音的数量。
因此,让我们为该函数编写代码-
为此的代码将是-
const str = 'This is a sample string, will be used to collect some data';
const countAlpha = str => {
return str.split('').reduce((acc, val) => {
const legend = 'aeiou';
let { vowels, consonants } = acc;
if(val.toLowerCase() === val.toUpperCase()){
return acc;
};
if(legend.includes(val.toLowerCase())){
vowels++;
}else{
consonants++;
};
return { vowels, consonants };
}, {
vowels: 0,
consonants: 0
});
};
console.log(countAlpha(str));输出结果
控制台中的输出将为-
{ vowels: 17, consonants: 29 }