The letters of my name aren't showing, and I can't find the error


#1


Hello, I've passed this lesson, but I'm not understanding it, nor am I getting the right "answer". Can someone please explain what am I doing wrong, and also, how to fix my errors.

Thank you.



This is what I am getting after saving my code.

[ 'R', 'R', 'R' ]
[ 'R', 'R', 'R' ]


var text = "This is a string and it is Richard's, \ it loves Richard and only Richard"

var myName = "Richard"

hits = []

for ( var i = 0; i <= text.length; i++ ){ 

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

   {hits.push(text[i])}}}

   console.log(hits)
   if(hits.length === 0)
 {
       console.log("Your name wasn't found!")
   } else {
       console.log(hits);
   }


#2

The {} means the 2nd for loop is executing nothing. Delete the {}

This line is telling the code to collect the 'R' from the text into the hits array. There are 3. Then you log hits to the console twice, which is why you see the 6 'R's. You should remove your first console.log(hits). Leave the one in your else statement.

Change the i in hits.push(text[i]) to a j. Why j? Your first loop passes through the text. When i matches 'R', the second loop passes through the text starting from 'R' since j is set to i. Then hits.push adds characters after 'R' into the hits array until the 2nd loop stops executing.

'R' appears in the text 3 times, meaning the 2nd loop executes 3 times. Your name should now appear in the log 3 times.


#3

Thank you so much. I understand why it didn't show up now.


#4

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