This nested for loop is causing me massive issues


#1


https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661#


Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.


/*jshint multistr:true */

var text = "This is some text and my name is Colt. Eaves Ashton Colt.";
var myName = "Colt";

var hits = [];

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


#2

first your if condition:

if(text[i] === myName)

it should check if text[i] equals the first letter of your name (myName[0])

then, the second for loop should run from the first letter of your name (i, thanks to your if condition) till the last letter (i + myName.length)


#3

thank you for you help! I am still confused with the second for loop. Could you please elaborate and an teach me :/? thank you so much!


#4

Those answers are so time consuming to write, i wrote two extensive ones:


Please read those first, if after this you have any questions you can ask


#5

could you maybe show me the physical code as to what the second for loop should be (in regards to my code)? That way I can follow your examples here with my own code?


#6

you got your code to work, right? So you can just use that to compare to this explanations? can i see an updated version of your code?


#7

/*jshint multistr:true */

var text = "This is some text and my name is Colt. Eaves Ashton Colt.";
var myName = "Colt";

var hits = [];

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

No, i have not gotten it to work :confused:


#8

now you made it worse, and there are even more mistakes in your code then i thought.

lets go back to your second for loop:
for(var j = i; j <myName.length; j++)

when i talked here about this:

i was referring to the condition which needs an upgrade. Also, remove this line:

 var newArray = [];

you can push your hits into the hits array you created earlier, otherwise you would empty the array the whole time.

Read the explanations first, so you better understand what you are dealing with (click the topic and scroll down to my explanations)


#9

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