2nd For Loop: myName[0] Instead of Hardcoded "Letter"


#1



My code is working, but I wanted to make what, to me, seems like an improvement, but it isn't working. Rather than saying, if(text[i] === "S"), I wanted to say, if(text[i] === myName[0]), but it's not working. This seems like a better way to do it rather than hardcoding an "S," because it would allow for the value of myName to be updated without breaking the code.

Can someone tell me why this doesn't work? Do I need to use a substring or something?

Thx for the help.


var text = "Lorem ipsum dolor sit amet, Seth consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore Seth magna aliqua. Ut enim ad minim veniam, quis nostrud Seth exercitation ullamco lab";

var myName = "Seth";

var hits = [];

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


#2

I tried to do what you're talking about, and it worked fine. try it again?

All I did was change your code to this:

var text = "Lorem ipsum dolor sit amet, Seth consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore Seth magna aliqua. Ut enim ad minim veniam, quis nostrud Seth exercitation ullamco lab";

var myName = "Seth";

var hits = [];

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

It worked great! :))))
Good idea by the way!
edit: It's always better to avoid hardcoding, in my opinion.
I like that you used the lorem ipsum, lol.


#3

And I like that you're homeschooled, because if you were bogged down by public education, you wouldn't know JS, be a code academy super user, or know what lorem ipsum is! It worked, btw, although I have no idea why it didn't work before. Thanks again, Kylea!


#4

this is true for me, because I get very distracted in a public environment, and people typically don't excel in school if they're public schooled (in my opinion) but I also know some extremely intelligent people in public school, and many programmers here did/are in public school as well.
But for me personally, homeschooling makes all the difference.

Glad that you got it to work, it is weird that you didn't get it to work right away, the browser either needed to be refreshed, or you had some kind of syntax error.


#5

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