jeudi 29 mars 2018

Javascript if and for loop confusion

I'm creating a Pig Latin translator and this function below checks for a double consonant.

Everything runs great up until it checks the word more in the function. It outputs the second letter as "m" as well. After that word the function seems to malfunction the word smile outputs the first and second letter to the console as "st". What confuses me is the last word in the array "string" ends up with the correct output to the console "st".

If anyone can look over my code and see something that I'm not seeing, I would be grateful. My JSFiddle is below.

var vowel = ["a", "e", "i", "o", "u"];
var consonant = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"];

doubleConsonate();

function doubleConsonate() { // add the sent as a parameter
  var theSent = ["ctt", "cheers", "to", "your", "mother", "chzek", "a", "few", "more", "smile", "its", "a", "string"];
  console.log("the word or phrase: " + theSent);
  var consonantCount;
  for (var i = 0; i < theSent.length; i++) {
    for (var j = 0; j < consonant.length; j++) {
      if (theSent[i].slice(0, 1) == consonant[j]) {
        console.log(theSent[i]);
        console.log("1st letter being checked is:  " + theSent[i].slice(0, 1));
      } else if (theSent[i].slice(1, 2) == consonant[j]) {
        //      consonantCount = true;
        console.log("2nd letter being checked is:  " + theSent[i].slice(1, 2));
      } //else if (consonantCount == true) {
      //theSent[i] = theSent[i].slice(2) + theSent[i].slice(1,2) + "ay";
      //consonantCount = false;
      //}
    }
    //console.log(consonantCount);
  }
  console.log(theSent);
}

Aucun commentaire:

Enregistrer un commentaire