Help understanding the code


#1



so everything works fine -
i just want to know - the second forfor(var j = i; j < (myName.length + i')`
why did they use j=i?
wheres the j came from and how does it work on the code?
thanks

"inside the soloLoop function, write a while loop that takes an initial condition that's true. Your loop should log "Looped once!" to the console, then change that initial condition to false.

MAKE SURE to set your condition to false in the body of your loop. Otherwise, you'll loop forever!"

`

text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {

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

}

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


#2

j should be equal to i .because you don't know where it'll meet the condition
(text[i] === "E")

now going through it

for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {

so loop will be start from 0.when i=30 it meets the condition.now second for loop

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

j=i is same as j=30(since i=30) and j < (myName.length + i) is same as 30<4+30 so it'll push hits.push(text[30]); that is E .

now j++
31< (4 + 30) //true prints r
j++
32< (4 + 30) //true prints i
j++
33< (4 + 30) //true prints c
j++
34< (4 + 30) //false

it'll need for the next time too when it'll meet the condition again.
after pushing Eric
it'll go to the first loop again .this time it'll meet the condition when i=50
so now j=50 .

i hope you've understand now.


#3

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