Unexpected Results


#1

This is my code:

/*jshint multistr:true */

var text = "Hey, Aaron. How is it going today. I hope aaron \
had a good day. Did aaron have a good day?";
var myName = "aaron";
var hits = [];

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

Here is what is logged to the console:

[ 'a',
'r',
'o',
'n',
'.',
'a',
'y',
'.',
' ',
' ',
'a',
'a',
'r',
'o',
'n',
'a',
'r',
'o',
'n',
' ',
'a',
'd',
' ',
'a',
' ',
'a',
' ',
'g',
'o',
'o',
'a',
'y',
'.',
' ',
' ',
'a',
'a',
'r',
'o',
'n',
'a',
'r',
'o',
'n',
' ',
'a',
'v',
'e',
' ',
'a',
'a',
' ',
'g',
'o',
'o',
'a',
'y',
'?',
undefined,
undefined ]

I can't figure out where I've goofed!


#2

You haven't 'goofed'. But, there may be a couple of things to address.

  • Start a name with a Capital letter
  • Be sure not to exceed the range of the data

We actually address both issues simply by capitalizing myName, and planting instances of it in that form in the text.

var myName = "Aaron";

In the conditional, we can query the first letter of myName (meaning it can be anything):

    if (myName[0] === text[i]) { ... }

Don't let the order I've written throw you. An identity is commutable.


#3

Thank you, that fixed it.

I actually didn't capitalize myName = aaron on purpose because I wanted to see if the code was case sensitive. I never thought of changing that one letter in the two places.


#4

It was a good test to throw in some lowercase. Smart. What we saw happening in the OP example was a result of every a triggering the inner loop. The a in day is what caused the two undefined at the end.