Javascript:计算字符串中元音的数量

Col*_*iel 6 javascript

我正在尝试计算字符串中元音的数量,但我的计数器似乎没有返回多个.有人可以告诉我我的代码有什么问题吗?谢谢!

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)

gue*_*314 6

return countfor循环,或使用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.testRegExp /[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)


Dar*_*hak 1

你也需要这样做。也使用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)

  • 首先,请不要回答这样的基本问题。他们不会给门户添加太多内容。其次,如果你选择回答,请添加解释。你是在为读者回答,而不仅仅是为OP回答 (2认同)