5. Stuck on for loop


#1


var text = "Hey, how are you \
doing? My name is James. \
Can Emma come out to play? \
No you may not james";
var myName = "James";
var hits = [];
//i will ++ till it reaches lengthVal of count
for (i = 0; i < text.length; i++) {
    if (text[i] === "J") {
        for (var j = i; j > (i+myName.length); j++  ) {
            hits.push(text[j]);
        };
    };
};


#2

For your second for loop, it seems your j will start iterating beyond the length of myName. Change the > to < and that should fix it.


#3

oh right in that loop we are checking to see if the letter found shares the same amount of letters
comparing < gives us that where as > goes onwards past the length of the name.


#4

Pretty much! Did it work?


#5

yes! it worked fine, sorry but its making me type atleast 20 letters


#6

Yeah, it's a rule to prevent spams on forums haha.
But I'm glad it worked! Have fun with the rest of the lessons!


#7

i'm also stuck on this problem here's my code

var text = "hey, my name is max, and max is da best"
var myName = ("max")
var hits = []
for(var i = 0; i < text.length; i++){
if (text[i] === "m"){
for(var j = i; j < (i + myName.length); j++:wink: {
hits.push(text[j]); };
};
};


#8

Hope this helps.

text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {
// If we find it, add characters up to
// the length of my name to the array
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

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


#9

Javascript doesn't recognize emojis. If you're going to have a semicolon after a closing bracket, then be sure that's the last bracket for that section of code. Otherwise it disrupts codeblocks from executing the way you intend.


#10

Thanks so much, this helped me out!!!


#11

when texting teens become programmers


#12

I have absolutely no idea what I'm doing wrong here. I keep crashing my browser window with what I think is an infinite loop, and I think I've narrowed it down to the second loop inside the 'if' statement. It's probably just a comma missing or something, but I've tried seemingly everything...

var text = "Hello, my name is Jon. I am studying Javascript. There are lots of people called Jon around. Jon is a common name.";
var myName = "Jon";
var hits = [];
for (var i=0; i < text.length; i++) {
if (text[i] === "J") {
for (var k = i; k = i+myName.length; k++) {
hits.push(text[k])
};
};
};


#13

Too many semicolons will disrupt your code from working the way you wish. Here's a link that will help your understanding of them:

https://www.codecademy.com/blog/78-your-guide-to-semicolons-in-javascript


#14

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