Second for loop


#1



My code behaves correctly however I don't understand WHY :slight_smile: If you look at the second FOR LOOP which is inside the IF statement, the way I read it is that it pushes only first letter of my name into the hits array.

Can someone explain me please which part of the code pushes all other letters of my name into the hits array?

Thank you!


var text = "Dani is not Dani but actually it is Dani by the way!"

var myName ="Dani"

var hits = []

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

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


#2

for(j=i; j<i + myName.length; j++){
            hits.push("D")
        }

can i ask why are you using second for loop if you want to push the valueD?

you should use

hits.push(text[j])

just try to understand why hits.push(text[j])

now here

if(hits = 0){

for checking two values we should use == or===

we use = for assignment



feel free to ask :slight_smile:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.