2017-02-23 40 views
5

我想計算字符串中元音的數量,但是我的計數器似乎不會返回多個元音。有人可以告訴我我的代碼有什麼問題嗎?謝謝!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; 
    } 
    console.log(count); 
    return count; 
    } 
} 
vowelCount('aide') 
+8

'返回計數;'搬出到用於環路 –

+3

嘗試'string.match(/ [AEIOU] /克).length' – Rajesh

+3

@Rajesh我最好使用'/ [AEIOU ]/ig' – Phil

回答

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') 
+2

首先,請不要回答這樣的基本問題。他們不會爲門戶增加太多內容。其次,如果您選擇回答,請添加說明。您正在爲讀者作出回答,而不僅僅是針對OP – Rajesh

+1

我只是創建整個字符串的小寫版本,而不是每個字符最多5次 – Phil

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);
返回

RegExp描述

字符集

[^xyz]甲否定或補充的字符集。也就是說,它匹配括號內未包含的任何內容。

標誌

i忽略大小寫

g全局匹配;找到所有的比賽,而不是第一場比賽


後停止使用傳播元素,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);


或者,而不是創建一個新字符串或新陣列獲得字符串的0財產或迭代字符,你可以使用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);

+1

使用正則表達式是更好的方法。 – 31piy

+1

@DarshakGajjar是的,'我'標誌用於匹配不區分大小寫。 – guest271314

+0

thnx解釋...和g標誌用什麼? – Darshak