I am learning JavaScript through Codecademy, but I have an issue. The code below is supposed to search through the text variable for my name in the myName variable and then push all of the individual letters to the hits array. The code that I have written is not correct but Codecademy says that it is correct and is going to let me move on in the lesson.
I have been trying to solve the issue that I am having with no luck. The problem is that when I run the hits.push(text); line it will output the entire variable but I have tried hits.push(text[i]); and get undefined for the result. Can someone please help me understand where I have made the mistake?
/*jshint multistr:true */
var text = "XsddfasASSFABrandonSFsdfdasBrandonsddfadfaBrandon";
var myName = "Brandon";
var hits = [];
for (i=0; i<=text.length;i++){
if (text[i]===myName[i]){
for(var x=i; x<i+myName.length;x++){
hits.push(text);
}
}
}
if (hits.length===0){
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
The best way I can think to explain your mistake is simply by walking through a bit of the logic of what you have written.
Your
forloop will iterateifor as many characters as there are in yourtextvariable, so: 49 times.The first run through your
forloop, wherei=0, you are checking to see iftext[0]is strictly equal tomyName[0].text[0] = XandmyName[0] = B. The strictly equals condition is not met, so the loop proceeds to incrementirepeat:text[1] = sandmyName[1] = r. This continues 47 more times, and the condition is never met.myName[i]is undefined after the first 7 loops.