No errors but my name doesn't show in the array


#1

My code:

var text = "Once upon a time in a far away land there was a frog named Eric. Eric! wanted to meet another frog to play soccer. Eric? was not good and needed to practice.";

var myName = "Eric";

var hits = [];

for (var i=0 ; i<text.length ; i++){
if (text[i] === "E"){
for (var j=i ; j<(i + myName.length) ; j++);{
hits.push(text[j]);
}
}
}

if (hits === 0){
console.log("Your name wasn't found!");
} else {
console.log(hits);
}


When I hit "Save and Submit" it lets me pass, but what's shown in the array is [ '.', '!', '?' ]

I put the punctuation so I could try and understand what's happening - seemingly it's pulling the unit AFTER my name ends, but I can't figure out why it's doing this instead of pulling my entire name like ['Eric' 'Eric 'Eric'], isn't that what should be happening?

Thanks!


#2

Looks like right after your j++) you have a sneaky semi-colon. That little guy causes your j loop to execute itself through to completion, at which point your j === i + myName.length and when you hits.push(text[j]) you're grabbing the next character AFTER your name.

Remove semi-colon, win.


#3

That totally worked !!! Thank you!

I still don't understand why that grabs solely the character after the name? Also, I'm not entirely clear why it pulls each character individually as ['E' , 'r' , 'i', 'c' ,'E', etc] instead of each one as ['Eric' , 'Eric' , 'Eric']? How much more complex is it to get the latter?


#4

To answer your first question let me shorten your text:

var text = "That Eric likes Eric-type things";
var myName = "Eric";
var hits = [];

for (var i = 0; i < text.length; i++) {
  // we are going to search the text one letter at a time
  if (text[i] === "E") {
    // if we find "E" run a loop that iterates "Eric".length times
    // starting at current position of "i" since that's where we found "E"
    for (var j = i; j < (i + myName.length); j++) {
      // push each letter from eric's name to our hits array one at a time
      hits.push(text[j]);
    }
  }
}

So when it finds an "E" it initiates a loop to grab that "E", then the "r" and so on for four letters. Each letter it grabs it push's into hits. That's why it's one letter at a time.

Your first version had a semicolon after the "j" for loop which acts like the end of a single empty expression. JavaScript allows you to run a loop without { } if the loop only has to execute a single expression.

// What your original code looked like to interpreter
for (var j = i; j < (i + myName.length); j++) {
  ;    // do nothing every iteration
}
hits.push(text[j]);

Thus you were pushing the character found at i + 4 in text which was always one character after your name.

Sweet bug, can't wait to throw that at a friend!


#5

Ahhhh got it!! Thank you very much !!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.