Doubt in second for loop 5


#1

/*jshint multistr:true */

var text = "Hey, how are you \
doing? My name is Teja.";
var myName = "Teja";
var hits = []
for (var i = 0; i < text.length; i++)
{
if(text[i] === 'T')
{
for(var j = i; j <=i + myName.length; j++)
{
hits.push(text[j]);
}
}
}

can anybody explain this line for (var j = i; j <=i + myName.length; j++) in the programme, I understood the before for loop but it is difficult to understand...what is the need of "i" in "i + myName.length" thanks in advance


#2

@netninja45863,
May be in Text format
https://discuss.codecademy.com/t/your-second-for-loop-stuck/30525/4?u=leonhard.wettengmx.n


#3

@netninja45863

----------------------First----------------------

We create variable j (it's our counter) and set its value to variable i.

Why: If variable i found the first letter of your name, we will have to find the rest of your letter composing your name.

Example

// variable I is equal to 0, he found the first letter of variable myName
// in variable text. variable j will be equal to variable I, that means
// variable j is equal to 0. Then, we will have to find the rest of the letter composing
// your name
var text = "myName bla bla bla myName";
var myName = "myName";

As long as variable j is smaller than the length of variable myName + variable i we increment variable j

Why: We want to have the whole name inside the hits array. We add variable i to the length of myName variable because we want to repeat until the j incrementation will be equal or superior to the length of variable myName + variable i. We increment variable j so it equal or superior to the length of myName + i (we don't want to generate an infinite loop).

Example

// We create variable j which is equal to 0 since variable i is equal to 0
// As long as j is smaller than the length of myName + i, we increment j
// This will put in hits array ['m', 'y', 'N', 'a', 'm', 'e'] since we took all the name
// and add in the array 
for(var j = i; j <=i + myName.length; j++) {
hits.push(text[j]);
}

Hope this helped you!:wink: