Your second "for" loop


#1

Hi, please help i'm not sure what is the problem my browser got crash when i run it, can you guys check my code

var text = "Hi Jay this is only a test text Jay";
var myName = "Jay";
var hits = [];
for (var i = 0; i < text.length; i++){
	if(text[i] === 'J'){
		for ( var j = i; j + myName.length; j++){
			hits.push(text[j]);
		}
	}
}

#2

There's a simple logic error here in your first for loop. :smile:

Let's break it down...

It says, in English, "create variable i and set it to zero; then while i is less than text.length increment i by one."

With that broken down, does that make sense?


#3

thanks for your reply hmm... your talking about this line right?

var i = 0; i < text.length; i++

what's wrong with that code?

can you please specify the exact line or code that im wrong?


#4

Oh, you know what - that line is perfectly fine. My bad, sorry.

It's this line where there's a logical error: var j = i; j + myName.length; j++.

The loop condition (middle one): j + myName.length in particular is at fault.

(There's no conditional operator.)


#5

thanks i got it now.. :sweat_smile:

var text = "Hi Jay this is only a test text Jay";
var myName = "Jay";
var hits = [];
for (var i = 0; i < text.length; i++){
	if(text[i] === 'J'){
		for (var j = i; j < i + myName.length; j++){
			hits.push(myName);
		}
	}
}

#6

Good job!

I'm glad you were able to find the solution by your own intellect!! Very good.


#7

I want to understand plz why I put i+myName.length?


#8

Make sure you are pushing the letters from the text and not the variable, myName.


#9

It is because the variable, j, currently has the value of i. So the condition will need to be greater than whatever j is. It does this by adding i to the length of your name.


#10

Can You plz trace the code with me ?
I wanna know what happen next after I push the first character to hits array Plz

var text="hadeerhadeer";'
var myname="hadeer"; length =6
var hit=[];

for(var i=0;i if(text[i]==='h') //true {
for(var j=i;j<(myName.length+i);j++){ //j=i=0 < 6+0 (myName.length+i)
hits.push(text[j]); //puch h into hits array
}
}
}
}