我们需要编写一个JavaScript函数,该函数接受包含英文字母的字符串,例如-
const str = 'This is a sample string, will be used to collect some data';
该函数应返回一个对象,该对象包含字符串中元音和辅音的数量,即输出应为-
{ vowels: 17, consonants: 29 }
以下是代码-
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 }