JavaScript字符串处理函数求助:元音占比判断与字符移除问题
问题排查:JavaScript removeVowel函数返回undefined的原因
需求说明
- 实现一个JavaScript函数
removeVowel,接收字符串参数并返回字符串,规则如下:- 统计字符串中的元音(a、e、i、o、u,忽略大小写)和辅音(仅统计字母,忽略非字母字符)数量:若元音数量多于辅音,判定为元音占多数,需移除所有元音;否则返回原字符串。
- 元音占多数时,需处理空格:首尾无空格,无连续空格;多单词保留单词间单个空格(若所有字符都被移除则返回空字符串)。
- 示例:输入
"hello"返回"hello",输入"adieu"返回"d"。
我的代码
function removeVowel(input) { //function that takes string as input //function returns an object containing vowel count without case in account. function vowelCount(input) { //to get vowel count using string.match let arrVowels = input.match(/[aeiouAEIOU]+?/g); //acc=accumulator, curr=current value let countVowCons= arrVowels.reduce(function (acc, curr) { if (typeof acc[curr.toLowerCase()] == 'undefined') { acc[curr.toLowerCase()] = 1; } else { acc[curr.toLowerCase()] += 1; } return acc; // the blank object below is default value of the acc (accumulator) }, {}); countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length; if(arrVowels > countVowCons.NoVowels) { //remove vowels from string & return new string const noVowels = input.replace(/[aeiou]/gi, '') } else { // return supplied string without modification return input } } }
测试结果
Expected: "hello" Received: undefined
Expected: "hrd d" Received: undefined
问题分析与修复方向
- 外层函数无返回值:外层
removeVowel仅定义了内部函数vowelCount,既没有调用它,也没有任何返回语句,导致函数默认返回undefined。 - 计数逻辑错误:
- 你用
arrVowels(元音组数组)直接和辅音数量比较,但实际需要统计的是元音总个数,而非匹配到的数组长度(比如"aa"会被匹配为一个数组元素,但实际是2个元音)。 - 变量名拼写错误:你给
countVowCons添加的属性是NonVowels,但判断时用了NoVowels,导致判断条件永远不成立。 - 未处理空匹配情况:当字符串中没有元音或辅音时,
input.match(...)会返回null,调用reduce或.length会直接抛出错误,需要先做空值处理。
- 你用
- 元音占多数时无返回值:内部函数中,当满足元音占多数的条件时,你定义了
noVowels变量,但没有返回它,也没有实现空格处理的逻辑。
修复后的示例代码
function removeVowel(input) { // 统计元音总个数,无匹配则返回空数组避免报错 const vowelList = input.match(/[aeiou]/gi) || []; // 统计辅音总个数(仅匹配字母类辅音,忽略非字母) const consonantList = input.match(/[bcdfghjklmnpqrstvwxyz]/gi) || []; if (vowelList.length > consonantList.length) { // 移除所有元音 let processedStr = input.replace(/[aeiou]/gi, ''); // 处理空格:去首尾空格,合并连续空格为单个 processedStr = processedStr.trim().replace(/\s+/g, ' '); return processedStr; } else { return input; } }
内容的提问来源于stack exchange,提问作者user18164791
相关产品推荐
相关产品推荐

