Your second 'for' loops to search name


#1


So, the console kept printing the letter S. It allowed me to move forward on the lesson. However, I feel like I didn't successfully code this correctly. Am I Right? What am I missing? Adding the .push function really threw me off. Not having anything strings in the array I created also threw me off. I appreciate the help.

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


var text = "Hey, my name is Steve. \
Is your name Steve too?";

var myName = "Steve";

var hits = [];

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


#2

Update: This is my code now. The console is printing the following:

[ 'S', 't', 'e', 'v', 'e', 'S', 't', 'e', 'v', 'e' ]

Does this look correct? I am so confused. haha

var text = "Hey, my name is Steve. \
Is your name is Steve too?";

var myName = "Steve";

var hits = [];

for(var i=0; i < text.length; i++){
if (text[i] === "S"){
    for (j = i; j < (i + myName.length); j++){
        hits.push(text[j]);
    }
}
}
if(hits.length === 0){
    console.log("Your name wasn't found");
}
else {
    console.log(hits);
}

#3

That is how it should look like, why are you still confused?


#4

Because I totally typed out the if/else function without thinking it thoroughly and it worked. So I was confused about how I made it work. Especially how I got the hits.length part of the condition. Also, the lesson provided us with j. Can j be substituted with another other letter as long as I use this letter as a platform?


#5

but you understand now? length is a built in function which gives you the length of the array. you compare if the length is zero (which means it is empty, your name wasn't found)

You can use any letter you want? You could even improve the program if you like


#6

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