mardi 1 décembre 2015

Capital Vowel: Inclusion of variable makes If statement behave strangely

I've been trying my hand at some coderbyte problems where I came across the Capital Vowel Problem. When I include the variable "matchTheChar" in my if-statement the code gives me a strange value

function VowelCount(str) { 
  var results=0;
  var str=str.toLowerCase();
  var matchTheChar= str.charAt(i);
  myRegExp=/[aeiou]/;
  for (var i=0; i<str.length; i++){
    if (myRegExp.test(matchTheChar)){
      results=results+1;
    }

  }  
  return results; 

}

However when I remove the variable and include the "str.charAt(i)" straight into the if-statement, the code works fine.

function VowelCount(str) { 
      var results=0;
      var str=str.toLowerCase();
      //var matchTheChar= str.charAt(i);
      myRegExp=/[aeiou]/;
      for (var i=0; i<str.length; i++){
        if (myRegExp.test(str.charAt(i))){
          results= results+1;
        }

      }  
      return results; 

    }

Why is this happening to the code?

Thanks for helping.

Aucun commentaire:

Enregistrer un commentaire