Your second "for" loop


#1

https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661

i need the explanation of star marked code , kindly anyone help me plz ?

var text = "Anita is tired. Anita is home. Anita needs to move.";
var myName = "Anita";
var hits = [];

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


#2

such explanations are extensive to write , please read some i (or other people, you can search the forum) i already wrote, i stored two of the answer:


If after this you still don't understand, if you ask me specifically what you don't understand, i will explain further.

Sorry, this might look lazy, but the answers i posted above took me like 30 minutes to write, 30 minutes each


#3
  • for(var j = i; j < (myName.length + i); j++)

in this code , why i hve to write j=i instead of j=0 and why can't write
j < myName.length like i<text.length and why hve to add i at the 2nd loop (myName.length + i).


#4

shouldn't the answers i have written (which you read) contain some of the answers?

because, i (thanks to your if condition) contains the index of the first letter of your name, so by assigning the value stored in i to j, you can now loop over your name. Now j has the index of the start of your name.

because the end of your name is at i + myName.length? this way, j has a end end a starting point, which exactly matches the position of your name


#5

would u plz give me the 2nd answer in another way ?


#6

also give me an example the result of adding i (sry to bother u again) .


#7

did you even read the topics i refered to? Please read those first.


#8

hmm, read it several times

i+myName.length is equal to text.length and the rest code is same as usual , am i right ?


#9

myName is "Anita"
myName.length is 5
text is "Anita is tired. Anita is home. Anita needs to move."
text.length is 51

Outer loop:
i is going to vary from 0 up to (text.length - 1) because you want to check all of text to see if you find any instances of myName[0] - which happens to be "A".

Inner loop:
j is going to vary from i up to (i + myName.length) because you only want to grab the same number of letters as you have in myName.


#10

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