Please explain this code


#1


/*jshint multistr:true */
var text = "Adison lives in New York"
var myName = "Adison";
var hits = [];
    for (i = 0; i < text.length; i++){
        // statement to check whether all letters is in text
        if(text[i]==="Adison"){
            // loop to test for names in text that add up in                  array
            for (j=i; j < (i + myName.length); j++){
                hits.push(text[j]);
                }
        }
        
        }
The code gave me an error: 
  
  
    Oops, try again.
    It looks like your second 'for' loop isn't pushing values to the 
hits array. Make sure it's working properly and that myName's text 
appears somewhere in the text variable.
  
but when i changed the if statement from:
             if(text[i]==="Adison") 
to:
             if(text[i]==="A")

i had a successful code. dont know why this work though. please someone should explain to me.


#2

i contains indexes, which you use to loop over text, agree? so text[i] you use the index to access the letter. so text[i] is always a single letter, looking for the first letter of your name. Once the first letter of your name is found, you use the second for loop to loop over your name

so it makes sense, that the if condition should be: if(text[i]==="A")


#3

oh! thanks. got that not quite clearly but i will first read over and over the comment again


#4

but do you understand it now?


#5

not yet...infact no. i dont understand


#6

is then too much to ask what you don't understand?

run this code:

var text = "Adison lives in New York"
var myName = "Adison";
var hits = [];
    for (i = 0; i < text.length; i++){
    console.log(text[i]);
}

see how text[i] is a single letter? The first for loop is only used to find the first letter of your name, of course the if condition then must if(text[i]==="A"), a single letter then never equal a whole name


#7

ok. got that line clearly now


#8

so you understand? Good :slight_smile:


#9

thanks :slight_smile::grinning:


#10

A post was split to a new topic: Python objects


#11