5. Your second "for" loop Syntax Error


#1


5. Your second "for" loop

SyntaxError: Syntax error

Not really sure what is wrong, I cant seem to find anything, Also is this how the code is suppost to be setup?

/*jshint multistr:true */
var text = "test Eli testing work Eli please work Eli"
var myName = "Eli";
var hits =[];
for(var i = 0; i < text.length; i ++) 
{
    if (text[i] === 'J') 
    }
    
     for (var j = i; j < i + myName.length; j ++) {
         if (text[j] === myName[j-i])
         {
         hits.push(text[j]);
            }


#2

im having problems on this one too, but on your code, in the first if statement... you search for "J" but there is no "J" in your variable called text. so the if statement is looking for a letter that is not there....


#3

There are a few things wrong, I'm not sure if it just a problem of you thinking logically about finding all the "Eli"s or if it a problem with what you think JavaScript needs to see to do what you want it to do. -- likely a bit of both. :slight_smile:

For example, here is your first for loop:

for(var i = 0; i < text.length; i ++) 
{
    if (text[i] === 'J') 
}

You've told JS to loop through your text string, one character at a time, looking for 'J'. As @ananomyx mentioned, you have no 'J' in your text string -- and even if you did, you haven't told JS to do anything when it finds one.

Do you see how that is a problem? Sorting that part out will start you off in the right direction.

Ask questions, tell us how you get on.


#4

Your "for" code should look like this for (var j = i; (j < myName.length + i); j ++)


#5

Thanks, the J was a typo and I revised it. Also I am put my second for loop in my if statement witch I think would make since because when the first for loop finds a 'E' in text it should start the second loop to find the rest of my name. I think this is how you would do that?

var text = "test Eli testing work Eli please work Eli"
var myName = "Eli";
var hits =[];
for(var i = 0; i < text.length; i ++) 
{
    if (text[i] === 'E') {
        for (var j = i; j < i + myName.length; j ++) {
         if (text[j] === myName[j-i])
         {
         hits.push(text[j]);
            }
    }
}

And I also get SyntaxError: Expected '}' when I run the code, where is that? I cant seem to find it.


#6

You haven't closed your if statement in your second for loop.


#7

Have a look at your { and }, you need to have an equal number of each. Sometimes it helps to see the pairs if you line the pairs up like you have done for your first for loop.


#8

thanks, got it all taken care of


#9

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