What's wrong with my code? For Loops S.5


#1

var text= "Once there was a tree in a field\
it was by a fellow Tom's house.  It sprouted the day\
Tom was born, and like he, it too grew.\
All the days long, Tom soaked up the sunlight,\
and he too grew, as the tree and he knew,\
all their days long, together they grew."

var myName= "Tom"

var hits = []

for ( var search = 0 ;  search <= text.length ; search++ ) {
    if ( text[search] === "T" ) {
        for (var search2 = search ; search2 < (myName.length + 1) ; search2++ ) { hits.push(text[search]) }
        }
}

I've been reading through others and comparing it to the first slide available and I just don't see what I did wrong. The error I am getting is that the second for loop doesn't push anything to the hits array...
And I just don't get it.


#2

Third time's the charm. I finally got it.
This isn't a premature "I nailed it" that will get edited off like the original one that was here.

I actually am on the next lesson now.


#3

What was your problem?
Also be careful with this:

search <= text.length

as the indices for a string of length n only go from 0 to n-1.


#4

I originally had myName.length + 1 rather than myname.length + search, just a goof that I made somehow, probably thinking about how I was using search and search 2 so I just associated 1 search with the number 1.


#5

Oh yes this is a problem as well:

search2 < (myName.length + 1)

the general idea is that by your first for loop you go through the whole string and examine every letter in it to see if it could be the first letter of your name. And if it is the first letter of you prepare it for examining it further, which means that you therefore store the next myName.length letters in an array. So if it is you're name you copy it letter by letter to the array. If it is not you'll find out later (probably). So what the second loop does is to start at where you found that first letter of your name and check the next myName.length letters. How is that done? simple

search2 = search // search is the position of your first letter
search2 < search + myName.length