What am I doing wrong?


#1

error message:
Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable.


/*jshint multistr:true */

var text = "As the blackbird in the spring";
var myName = "David";
var hits = [] ;

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


#2

It seems like you've got an extra set of curly bracket for the first for loop. There's no need for brackets.


#3

Ah, thanks for the reply but I tried taking them off and still no luck. We must go deeper


#4

Okay, let's put this together and see now:

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

#5

Thank you, but that didn't work either.

I was playing around with it and ended up with this:

/*jshint multistr:true */

var text = "As the blackbird in the spring David";

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

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

and it worked. All I did was change the text variable by adding in David at the end.
Anyone have any idea what the ■■■■ is going on?

The more I learn this the more I realize how much I don't know. lol.


#6

Not really.

I should have seen that. The text variable needed to have your name in it. It needs to find myName in text.

So, that's what's happening.


#7

@terawhiz27097 Your goal of this exercise is to find your name in the text and you made for loop that starts if program finds any word who begin with 'D', but apparently you dont have any word in text who begins with 'D'. So if you want to continue without errors and also without word 'David' you can add this code:

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

And now in console should be written Your name wasn't found!

var myName = ''David'' is there just to tell you length of your word nothing else, so you could change it in '
var myName = ''Hogar'' and everthing will be the same.

I expect now it will be a little clearer for you.
p.s. Everything is fine with your curly brackets, they are not the cause of error.


#8

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