Why j < (i+ myName.length);


#1

So, this code confuses me:

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

    }
}

};

First we start at 0th position of text variable, and increase counter i by 1, if we get value of variable text (at some position of counter i) to be equal to our starting letter we enter second for loop.

We set counter j to be equal to position of counter i. We need counter j to be smaller than ( counter i plus length of our name ). This confuses me, I get it that we need to push each letter of our name.
If my name is "Dean", then starting from "D", plus 1 is e and so on... I push letter by letter and when I reach "n" I go out of second for loop.

Why is i neccessary? Can't it be just j < myName.length + 1? Since we already assigned the counter j to start from i and since text[i] === "D" why doesn't it work?


#2

Well arrays and strings start counting at 0 so a string of "Dean" has 4 letters which are indexed by 0,1,2,3 so if you use "Dean".length which is 4 than your index need to be smaller than 4 because 4 is not a valuable index. Same here for text:

for(i = 0; i <=text.length; i++){


#3

I get that, maybe I haven't phrased my question good.

Why do we need j < (i + myName.length)?

Why i? Is it from position i, isn't j already at position i

Can someone explain what happens in all these steps?


#4

yeah, I tried to do j < (myName.length + 1) also. Then, whilst trying to figure out what was wrong with the hits.push, I noticed that everyone else was doing j = i

it might be because if i === 'letter of your name' by making j = i you're narrowing down the search further to just that occassion of that first letter?

if that makes sense...

edit: nope, i've confused myself...


#5

Ohhhh, I think it's because myName +i is the loop......


#6

Sry for the late response. Well i is per definition the first letter of your name as it made the condition becomes true. So what you want to do is to grab the next myName.length letters to your hits array (one by one for ... reasons...). So if you are at i and want to go myName.length steps well you make j become I and go to i+myName.length. Because

start = i 
end = i+myName.length
numberOfLoops = end-start = myName.length

And the reason why you should not use j instead is because j is changing, sure in the first loop it is i and then you do j++ so you basically end up at something like a dog trying to catch his own tail as although j keeps increasing your stopping conditions (which depends on j) keeps increasing in the same way.


#7

Thank you very much, it explains all now.