2015-05-29 28 views
0

必須調試這個類的某段代碼,我不知道爲什麼這個JS計算所有字母而不僅僅是元音。爲什麼此代碼不僅計算元音?

var text, i, sLength, myChar; 
var count; 
var text = prompt("Type a phrase please"); //put var in front of text and fixed " in place of ' in front of type 
count = 0; 
for (i = 1; i <= text.length; i+= 1){ 
    myChar = text[i]; 
    if (myChar == 'a' || 'o' || 'e' || 'u'){ //switched to the proper vowels 
     count += 1; 
     console.log('Vowel:', myChar); 
    } 
    console.log(myChar, count); 
} 
alert (count); //put the count in() instead of alert 
+0

myChar == '一個' || myChar =='o'... – 2015-05-29 04:21:21

+2

...你錯過了'我' – 2015-05-29 04:22:25

回答

0

執行比較的行沒有正確執行檢查。它應該是:

if (myChar == 'a' || myChar == 'o' || myChar == 'e' || myChar == 'u') 
0

正確的JS就是這個。

var text, i, sLength, myChar; 
 
var count; 
 
var text = prompt("Type a phrase please"); //put var in front of text and fixed " in place of ' in front of type 
 
count = 0; 
 
for (i = 1; i <= text.length; i+= 1){ 
 
    myChar = text[i]; 
 
    if (myChar == 'a' || myChar == 'o' || myChar =='e' || myChar == 'u'){ //switched to the proper vowels 
 
     count += 1; 
 
     console.log('Vowel:', myChar); 
 
    } 
 
    console.log(myChar, count); 
 
} 
 
alert (count)

你不工作的原因是因爲它是問「O」是否爲真時,你說的表達|| 'o',並且由於字符串文字不是虛假值(0,「」,null,undefined,false),它對於循環的每次迭代都保持爲真。

0

超級快捷途徑

function countVowels (string) { 
    return string.match(/a|e|i|o|u/g).length; 
} 

用途爲:

alert(countVowels(prompt("Type a phrase please"))); 


if是無效的條件。如果你想快速地檢查值的一些選項之一,請嘗試以下操作:

if (['a', 'e', 'i', 'o', 'u'].indexOf(myChar) > -1) { 
} 


功能!

function hasOptions (c) { 
    return arguments.splice(1).indexOf(c); 
} 

然後

if (hasOptions(myChar, 'a', 'e', 'i', 'o', 'u')) 
相關問題