Don't understant why my code isn't working in second 'for' loop


var text = 'Some text with Howdy. Howdy-ho!';
var myName = 'Howdy';
var hits = [];

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

Can you help me to understand why i got "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. " with this code and when i change "myName[i]" to "myName[0]" it is working well?


because i will loop over text, which contains a much longer string then myName, so you will run out of string

besides, this if condition is to check if the current character in text string equals the first character of you name (which means, your name is found inside text

and, using myName[i] will not be true, so your name is never pushed into the hits array, which is why you get an error


It will take first letter + myName.length and push it into the hits array?


the first loop loops over text

then, once your if statement finds a match, your second for loop will loop over your name in text, and push it into the hits array letter by letter


Thatnk you for the answer!


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