6 :: .push() syntax not pushing - Help?


#1

I got the error message

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.

But I don't really understand the push function. I'd assumed it would work as I'd written in my code as follows:

var text = "My name is Matt and I love nutella";

var myName ="Matt";

var hits = [];

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

Can you help me find the glaring error in my code? :slight_smile:


#2
 j < i +myName.length

should be,

hits.push(text[j]);

#3

You're a genius and a scholar. Thanks for your help!


#4

Hi, I also had the same error but I can't figure out what I am doing wrong. I also have hits.push(text[j]); but I get the same error message.

Error: It looks like your second 'for' loop isn't pushing values to the hits array.

var text = "Hi my name is Cecile"; 

var myName = "Cecile";

var hits = [];

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

#5

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

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

Don't ask me why, but it needs to be like that...

Apart from that I can't find any reasons why it shouldn't work..


#6

I made another change and got it!

Megasurfer- shouldn't you be checking if text[i] === 'M' and not just if text[0] ==='M'? Right now you are only checking if the 1st index of all the text equals the first letter of your name


#7

You're totally right, and I literally just realised 2 seconds before reading your comment.

Here I am wracking my brain trying to figure out what I've done to make it not work, and it's something so simple! Thanks for letting me know!