I am getting an **Out Of Memory** error and my code seems to be correct


#1



I am getting an Out Of Memory error and my code seems to be correct.


var text = 'John, How are doing, John?';
var myName = 'John';
var hits = [];

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


#2

this:

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

is an infinity loop.

look at your condition:

i < (myName.length + i)

and you are increasing j (j++) how can this condition ever become false? How do you think the condition should be?


#3

stetim94,

Thank you for replying to my question. I guess I'm not really understanding how the second loop middle code
i < (myName.length + i); works.

I'm not sure, but I think I see what you are talking about in the code.

I originally had:

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

for my second loop code but I was getting a different error that stated "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." So I thought by changing the second for loop would fix the issue and I change it to

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

and the first error went away but then I got a Out of Memory error and I got more confused the more I change it. I know that the second for loop is in a forever loop but I don't understand where or on how to fix it. It gets very frustrating after spending 5 hours trying to research the forum and understand the hints in the exercise to figure out why I'm getting two different errors. Can you recommend another reference I can look up to help me understand the second loop concept further and to look up the meaning of the first error? I've looked on the forum and Google and I am still not able to figure out what the first error mean or what I need to do and why I'm doing what I am doing for the second loop.


#4

writing explanations on the second for loop are extensive. i wrote one here:

in essence, you use j to loop over the letters of your name, the second for loop should last while i + myName.length is greater then j

here:

var j = i

you copy the value of i to j, i contained the first letter of your name thanks to your if condition.

so know you can use j to loop over your name, we can get the end of your name by using i (which is the start of your name) + myName.length

so the condition in the second for loop should contain j somewhere


#5

Ok thank you very much for helping me. I appreciate it. It now works

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

to this

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

worked for me and i understand the concept now. thanks again


#6