Wrong output it seems


#1

Hi, maybe someone can clarify this for me.

I have tried numerous options to get the code right for this topic (finding your name in text). and for some reason it looks like I'm getting the wrong output (or I do not understand 100% which output I should be expecting).

My code is as follows:

/*jshint multistr:true */
var text = "Hi There. My name is Ronald Koornneef. Don't you think that Ronald is a very nice name? I heard that Ronald is actually the greatest name in the world!! Hail to all Ronalds!!";
var myName = "Ronald";
var 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[j]);
}
}
}

And like this the output is 24. It looks like it is pushing all the letters of my name (4x in text). 4x6=24. This seems logical because if I add my name in the text once more the output is 30. I was expecting just 6 as output.

Can anyone see where I went wrong on this case??

Thanks in advance! (


#2

Here you use <= where you should use <:

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

But this has nothing to do with the number you see. Actually well spotted the number is the number of letters in your name times the occurence or in other words the length of your hits array. That is a side effect of .push() to return the new lenght of the array and as this is the last value in your code it is echoed on the console. If you want to see how often your name was found maybe add a counter inside of your if statement.

var nameCount = 0;
...
if (text[i] === "R") {
nameCount++;
...

and if you want to see what is inside of hits why not console.log(hits); at the end of the code? This would also help to get rid of the number.


#3

Thanks. I was not sure if I did something wrong or if I was supposed to get a higher number.

I did add the console.log(hits) line and again it outputs 24

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

if I do it with:

if (hits.length === 0) {
console.log("Your name wasn't found"); }
else {
console.log(hits);
}
it simply prints
'R'
'o'
'n'
'a'
'l'
'd'

I think there is no mistake here, I was just expecting the result to be the amount of time my name (my entire name) is in text, instead of the amount of characters of my name.

I'll true to fiddle around with your idea for the counter!


#4

Yes that is actually correct. To be honest I don't really see much sense in it either to sum up the letters of your name other than practicing loops...
As said for the number of times you could try the counter. I'm off for a bit but if you figured it out or have any questions about this feel free to ask.


#5

Well practice makes perfect. I'm quite new to programming, but it is interesting so I'm motivated to learn as mush as possible. Therefore I shall be posting more questions in the future for sure :smile: