计算元音、辅音的出现次数 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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 }