Second For Loop: Wrong number of hits?


#1

My code works fine but shows 6 hits each time. Can someone help me understand where it is getting 6 hits from?

var text = "Hi, my name is chris";
var myName = "chris";
var hits = [];

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


#2

Hi on your second for loops try to remove the = to <=


#3

After running a console log on hits i do see why its showing 6 now but why the 6th "undefined" character?


#4

ahhhhh. Thank you very much. Now i understand why i was getting the undefined character too. ( because of the i + myName.length for anyone else wondering)


#5

If you output hits, you will see that hits = ['c', 'h', 'r', 'i', 's']. Or it should be. You will one additional character because you used <= and it will push loop into unknown area and take something that is not defined. That's why you have 6 characters instead of 5 in your hits variable. Just use <.