Second for loop - Cant find the error here. It gives no syntax errors but says the results aren't being pushed to hits


#1

Hi

I am stuck on this exercise "Your second for loop". It gives me this error:

Oops, try again.
It looks like your second 'for' loop isn't pushing values to the
hits array. Make sure it's working properly and that myName's text
appears somewhere in the text variable.

Can anyone spot my error? I've gone over a few posts and I can't find anything...


/*jshint multistr:true */
var text = "Hello I have a Penguin pet. He is a great pet. The thing about \
my Penguin is that he will only eat fish and gummybears. I guess he is an odd penguin.";

var myName = "Penguin";

var hits = [];

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


#2

well, look:

var text = "Hello I have a Penguin pet. He is a great pet. The thing about \
my Penguin is that he will only eat fish and gummybears. I guess he is an odd penguin.";

var myName = "Penguin";

var hits = [];

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

nothing gets pushed into hits array. Why?

here:

for (var j = i; j > i + myName.length

lets say i is 16, this would mean:

for (16; 16 > 16 + 7

This condition is false, so the loop never runs. Maybe you need to change the condition of your second for loop?


#3

Thanks.. I was staring myself blind on this on.

Fixed now, appreciate the help.


#4

are you sure? You also saw that only the first letter of your name was pushed into your hits array?


#6

Yea I noticed that but it was an easy fix.


#7

It is, i just wanted to make sure you saw it and understood it :slight_smile:


#8

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