Passed lesson but array hit remains empty


#1

Ok, here's my code that always logs "Your name wasn't found" to the console. I don't get why array hit remains empty and would greatly appreciate any explanation!

text = "Lorem ipsum Martin dolor Martin sit amet Martin";

var myName = "Martin";
var hits = [];

for(var i = 0; i <= text.length; i++) { //go through text up to and including the last character, so I put <=
if (text[i] === "M") {
for (var j = i; i <= myName.length; j++) { //if i==="M", so j too, push characters up to and including last character of myName to hits
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}


#2

Add prints to see how far it gets, and then start inspecting the conditions. Compare them to what they should be doing.


#3

I don't know what prints is or how to add it.


#4

console.log("I'm in the inner loop! The current letter is: ", text[j]);

#5

Well, thanks for trying to help but I don't know what to do with that. Maybe you could just use my code above?


#6

You could insert it in your code to make your code tell you what it is doing step by step. You can then read that output to tell where it goes wrong. You may need to add more prints like that since it's doing more than just one thing.


#7

I'm having trouble with this question to. Can you please just put the whole code correctly.


#8

Wouldn't that defeat the purpose of the exercise?

Make sure to have understood what's supposed to happen, convince yourself of that doing those things adds up to the desired result. Then start implementing those things one at a time. If you don't know how to do some specific thing, look up how to do that or ask about it!

You might find it helpful to start by writing comments that describe in plain English what's supposed to happen.

// Iterate through each character in the text

// If the current character is the same as the first letter of the name

    // then add a number of characters equal to the length of the name
    // starting at the current position of the outer loop, and ending when
    // the correct amount of characters have been added

// finally, present the result

#9

I found the error first you need to remove all the <= and put just < and on your
for (var j = i; i < myName.length; j++) there is a problem you need to set
..... j < (myName.lenght + 1); j++)
I hope I could Help you


#10

@wizmarco
That's the right track, but not quite sufficient

If the name starts a hundred characters in, and the name is length 3, then the inner loop should stop after 102, not at after myName.length ..which is one character too much as well, because the last index when starting from 0 is the length-1, but here the first index is not 0, and not 1, it's 100, or whatever value the index of the outer loop is at.