What's wrong with the loop?


#1

I can't seem to figure out what's wrong with my code, ...it shows an empty array when i run it. it does not push the characters.

var text = "mr charles sent mr oliver charles\ charles wasn't really intersted.";

var myName = "charles";

var hits = [];

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

#2

Each for loop needs to stand on its own but just in the body of the if statement.

See this line, I don't seem to understand what's going on.

See suggestion below:

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

#3

Thanks! ...it worked!


#4

And hope it was also understood.

All the best!

Have fun coding! :slight_smile:


#5

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