Why am I getting undefined print out here?


#1

Hey guys, I have my name being printed but also a ton of undefined characters, any idea what I did wrong?

      /*jshint multistr:true */

    var text = "name name name name \
    I love text and strings wow ";

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


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

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

#2

Okay, let's say for starters that you actually search for the first letter in your 'name'. The outcome, assuming the code is correct will be,

[ 'n', 'a', 'm', 'e', 'n', 'a', 'm', 'e', 'n', 'a', 'm', 'e', 'n', 'a', 'm', 'e','n', 'd', ' ', 's', 'n', 'g', 's', ' ' ]

However, we know that the code is not correct.

    hits.push(myName[j]);

which should read,

    hits.push(text[j]);

It also helps if we stay a little closer to the instructions, and the example given in lesson 1 and use proper names. How does a bank address us? Wee Gillis, is a proper name. It makes the program a little more precise, since JS is case sensitive and sees 'W' as different from 'w'.

It also helps if we actually search for the first letter in our name:

if (text[i] === "W")
//or
if (text[i] === myName[0])

Lastly,

should be,

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