5. Your second "for" loop


#1


5. Your second "for" loop


I am getting the error message: SyntaxError: Unexpected Token. I don't understand why my code does not work.


/*jshint multistr:true */
var text = "Hello, how are you? my name is John Smith";
var myName = "John Smith";
var hits = [];

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


#2

You can either place a closing parentheses on this line after i or you can remove the parentheses before myName.


#3

There a syntax error in your second for loop. Please compare it with my code. Hope it works for you because it did for me.
var text = "Hello, how are you? my name is John Smith";
var myName = "John Smith";
var hits = [];

for (var i = 0; i<text.length; i++) {

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

}


#4

Check your syntax on this line for the push.


#5
  1. text[i] === 'H' : Not a syntax error but logical error. You should be checking from the start of your name. The best way to prevent such mistake is to check like this :
    if (text[i] === myName[0]). This will always check for the first alphabet in your myName string.

  2. oinkywoinky:

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

j < (myName.length + i) : Closing the parantheses in pairs is extremely important in coding. You missed to close one parantheses in this statement and that's a syntax error. Hence, the program won't compile.

3 . hits.push[(text[j])]; : push is a method. Methods are always represented like method(). Square brackets are used for arrays and strings. This line treats push as an array because of the square brackets. So it should simply be hits.push(text[j]);


#7

var text = "Hello, how are you? my name is John Smith";
var myName = "John Smith";
var hits = [];

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


#8

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