我正在尝试计算字符串中元音的数量,但我的计数器似乎没有返回多个.有人可以告诉我我的代码有什么问题吗?谢谢!
var vowelCount = function(str){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str[i] == 'a' || str[i] == 'i' || str[i] == 'o' ||str[i] == 'e' ||str[i] == 'u'){
count+=1;
}
}
return count;
}
console.log(vowelCount('aide'));
Run Code Online (Sandbox Code Playgroud)
return count外for循环,或使用RegExp /[^aeiou]/ig作为第一个参数.replace()与""作为替换字符串,得到.legnth的返回的字符串.replace()
vowelLength = "aide".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);
vowelLength = "gggg".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);Run Code Online (Sandbox Code Playgroud)
RegExp 描述
字符集
[^xyz]否定或补充的字符集.也就是说,它匹配括号中未包含的任何内容.
旗
i 忽略案例
g全球比赛; 找到所有匹配而不是在第一场比赛后停止
使用spread元素Array.prototype.reduce(),String.prototype.indexOf()或String.prototype.contains()支持的位置
const v = "aeiouAEIOU";
var vowelLength = [..."aide"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);
var vowelLength = [..."gggg"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);Run Code Online (Sandbox Code Playgroud)
或者,而不是创建一个新的字符串或新的数组来获得.length字符串的财产或迭代字符,你可以使用for..of循环,RegExp.prototype.test用RegExp /[aeiou]/i递增的变量初始设置为0,如果.test()计算结果为true对角色通过.
var [re, vowelLength] = [/[aeiou]/i, 0];
for (let c of "aide") re.test(c) && ++vowelLength;
console.log(vowelLength);
vowelLength = 0;
for (let c of "gggg") re.test(c) && ++vowelLength;
console.log(vowelLength); Run Code Online (Sandbox Code Playgroud)
你也需要这样做。也使用toLowerCase()
var vowelCount = function(str){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str[i].toLowerCase() == 'a' || str[i].toLowerCase() == 'i' || str[i].toLowerCase() == 'o' ||str[i].toLowerCase() == 'e' ||str[i].toLowerCase() == 'u'){
count+=1;
}
}
return count;
}
vowelCount('aide')
Run Code Online (Sandbox Code Playgroud)