Have some questions in regards to this code


#1

Here is my code:

/*jshint multistr:true */
var text = "Moje ime je Ivan, ja sam najbolji, Ivan.";
var myName = "Ivan";
var hits = [];
for(i=0;i

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

}

console.log(hits);

  1. I don't really understand data that im pushing into my hits array, shouldn't i push the whole name - Ivan, and not single out letters ?

  2. Also why doesn't this code push the word 'ime' too, it starts with i
    ^Got this one while i was typing out the question, it's because it isn't capital i

I don't know why my code got butchered, here's pastebin link:


#2

It is pushing your whole name to hits array? It is just doing it letter by letter, which is why you have the second for loop, if i run your code, i get the whole name:

You understand how the second for loop works? Because that is rather important

I wrote an extensive answer about that here, might be worth reading


#3

i do not fully understand second loop, i'll look into your link, thanks for helping.

p.s. i get the same output as you, was just wondering am i supposed to get ["Ivan", "Ivan"] output.


#4

Well, first read the link i posted, to better understand the second for loop, because it will also your second question, you could also add a console.log to see what is happening:

var text = "Moje ime je Ivan, ja sam najbolji, Ivan.";
var myName = "Ivan";
var hits = [];
for(i=0;i<text.length;i++){
    
    if(text[i]==="I"){
        for(j=i;j<i+myName.length;j++){
            console.log(text[j])
            hits.push(text[j]);
        }
    }
    
    }
console.log(hits);

If after reading the post i linked to, and you still have questions about the second for loop, do ask


#5

i do understand now, because for goes character by character.
if first letter is I then returns v and then a and then n

thank you