Not finding my name


#1

https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/6?curriculum_id=506324b3a7dffd00020bf661#

The code is not finding my name. console.log says my name was not found, but my name is in the text.


/*jshint multistr:true */

var text = "text text text."
var myName = "Dorne"
var hits = []

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

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

#2

Is your name in this text? The instructions tell us to be sure our name is in the text at least once.


#3

Yes it's in there a couple times.

var text = "Who is she writing to?/ Assuming that this is a letter of/ consequence my first guess would be/ Dorne. They hate the Lannisters, and/ they just got new management. Wouldn't/ it be awesome to have a scene with/ Danny landing in Dorne and Lady Olenna/ shows up complaining about the heat?/ On the other hand, the Reach and/ Dorne don't get along at all. Also/ House Tyrell has bet all their chips/ on Tommy B so I'd imagine they'll be/ against Daenerys when she shows up."
var myName = "Dorne"


#4

Then why the posted code in the OP?


#5

Just wanted to make the post easier to read. Sorry if i made it confusing.


#6

Okay, moving on to the real error.

if (hits.length === 0) {

#7

It's giving me this

[ 'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D',
'D' ]


#8

And with that we discover the elephant in the room.

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

As a general practice we do not use capital letters for variables. The normal practice in loops is to use i, j, and k as iterator variables where the variable represents an index.

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

#9

Got it! Finially. Thanks a bunch for that. Man, Javascript is tough.


#10

It gets easier, but it will always take a lot of thought and effort. Keep working at it and be patient with yourself. Expect to fail, and learn from each experience. We just keep getting back up on the horse.


#11

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