5. Your second "for" loop


#1

Hello, I am stuck this lesson:

/*jshint multistr:true */
var text = "my name is Amanda and I Amanda am \
learning JavaScript";
var myName = "Amanda";
var hits = [];
for(var i=0; i<text.length; i++); {
    if (text[i] ==="A"); {
        for(var j = i; j<i+text.length; j++);
            hits.push(text[j]);
            console.log(hits);
        }
    }

#3

It was me, but it wasn't a response, it was a notification you received to tell you that I moved your topic to a different category.

I'll try and help though. Give me a sec..


#4

Hi,
Try removing semicolons after for loops as well as if loop. Also, place a opening curly brace to the second for loop.


#5

Not sure I am following. Don't I need semicolons in my for loops?

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


#6

Hi,

for loops should be written like this:

for(condition) {
//your code
}

Also if loop should be written like below:

if (condition) {
//your code
}

#7

Just doing that won't work.

@amandakoster, you need to;
- Remove the semicolons here:

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

Then you need to change this:

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

to

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

(else it'll loop too much)
and add a brace here:

for(var j = i; j<i+text.length; j++); // remove semicolon, add {

and on the last line (so bottom three lines look like this:

        }
    }
}

Any questions?


#8

Only at the end of statements:

return true;
console.log("Hello, world");

#9

Thank you. Something 'worked' and here is the output. However, I thought it was looking for the # of occurainces my name appeared n the 1st string.

[ 'A' ]
[ 'A', 'm' ]
[ 'A', 'm', 'a' ]
[ 'A', 'm', 'a', 'n' ]
[ 'A', 'm', 'a', 'n', 'd' ]
[ 'A', 'm', 'a', 'n', 'd', 'a' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A', 'm' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A', 'm', 'a' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A', 'm', 'a', 'n' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A', 'm', 'a', 'n', 'd' ]
[ 'A', 'm', 'a', 'n', 'd', 'a', 'A', 'm', 'a', 'n', 'd', 'a' ]


#10

You're seeing that in the last line though...? Does it pass?


#11

The code passed, but my name has 6 characters. Why did it print 12 characters?

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


#12

Your name was in the string twice,
12/6 = 2
2 instances of your name in the string.

It printed your name twice, because your name was in it twice. :stuck_out_tongue:


#14

var text = "my name is Michelle and I love
learning JavaScript";
var myName = "Michelle";
var hits = [];
for(var i=0; i<text.length; i++){
if (text[i] ==="M") {
for(var j = i; j<i+myName.length; j++) {
hits.push(text[j]);
console.log(hits);
}
}
}