Javascript 我正在尝试编写一个函数,返回字符串中的元音数
这是我的代码,但我在控制台中没有定义Javascript 我正在尝试编写一个函数,返回字符串中的元音数,javascript,Javascript,这是我的代码,但我在控制台中没有定义 函数numof元音(字符串){ 让计数=0; string=string.split(“”); 常量元音=函数(字符串){ for(设i=0;i>string.length;i++){ 如果(字符串[i].toLowerCase()=='a'| |字符串[i].toLowerCase()=='e'| |字符串[i].toLowerCase()=='i'| |字符串[i].toLowerCase()=='o'| |字符串[i]{ 计数+=1; } 返回计数;
函数numof元音(字符串){
让计数=0;
string=string.split(“”);
常量元音=函数(字符串){
for(设i=0;i>string.length;i++){
如果(字符串[i].toLowerCase()=='a'| |字符串[i].toLowerCase()=='e'| |字符串[i].toLowerCase()=='i'| |字符串[i].toLowerCase()=='o'| |字符串[i]{
计数+=1;
}
返回计数;
}
};
}
console.log(Numof元音(‘黄色潜水艇’)代码>您没有从Numof元音返回值,也不需要拆分字符串,您可以对其进行迭代,查看下面的代码:
函数numof元音(字符串){
让计数=0;
for(设i=0;i这里是正确的代码
第一个问题是i>string.length
应该是i
infor
循环第二个问题是返回计数
应该是在循环完成之后,第三个问题是元音
函数,它从未在numofuels
内部调用过
function numOfVowels(string) {
let count = 0;
string = string.split('');
const vowels = function(string) {
for (let i = 0; i < string.length; i++) {
if (string[i].toLowerCase() === 'a' || string[i].toLowerCase() === 'e' || string[i].toLowerCase() === 'i' || string[i].toLowerCase() === 'o' || string[i].toLowerCase() === 'u'){
count+= 1;
}
}
return count;
};
return vowels(string);
}
console.log(numOfVowels('Yellow Submarine'));
函数numof元音(字符串){
让计数=0;
string=string.split(“”);
常量元音=函数(字符串){
for(设i=0;i
这里有几个问题:
声明但不调用函数元音
您的返回语句返回计数代码>在循环内部,并将在第一次迭代时返回
for
循环中的条件正在使用
,它应该使用
(/[aeiou]/i.test(char))?count+1:count,0);
//使用过滤器
让count2=s.split(“”).filter(char=>/[aeiou]/i.test(char)).length;
console.log(count1);
console.log(count2)代码>如果您想要一个更短的实现(只需说一句):
还有,什么是未定义的?你调试过了吗?你再也不会从numofequents
返回了。我相信Yellow subside
返回时没有定义或count'
--这是我刚才仔细检查过的计数。你知道如果你调用元音
,它将在第一次迭代时返回吗?@JamesClarke你永远不会从numofewales
返回,你也永远不会调用元音
。不会出现类型错误,循环只运行一次。除了这个非常好和全面的答案@克里斯托夫:是的,我的意思是如果2号修好了。谢谢你指出。不会有错误的。如果不满足该条件,则不会执行代码块。
countvowels=word=>word.split("").reduce((c,l)=>(["a","e","i","o","u"].indexOf(l.toLowerCase())+1)?++c:c,0);