为什么这个代码不仅计数元音? [英] Why does this code not only count vowels?
本文介绍了为什么这个代码不仅计数元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
必须调试此类的某段代码,我无法弄清楚为什么这个JS计数所有的字母,而不仅仅是元音。
Have to debug a certain segment of code for this class and I can't figure out why this JS counts all letters and not just vowels.
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
推荐答案
超短路
Super Short Way
function countVowels (string) {
return string.match(/a|e|i|o|u/g).length;
}
用作: / p>
Use as:
alert(countVowels(prompt("Type a phrase please")));
如果是无效的条件,您是
希望快速检查一个值是否是某些选项之一,请尝试以下操作:
You're if
is an invalid condition. If you wish to quickly check if a value is one of some options, try the following:
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'))
这篇关于为什么这个代码不仅计数元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文