7/7 The code works But


#1

var text = "blah blah Brandoblah blah blah \
Brando blah blah blah Brando";
var myName = "Brandon";
var hits = [];
for (var i=0; i < text.length; i++){
if(text[i] === "o"){
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);
};

So this code works but it prints out some letters and then for the rest it prints out undefined. I would like to know so i can fix this but i dont know what happened. Can someone please help?


#2

Try changing your if statement:

into

if(text[i] === "B"){

because your name is "Brandon", and it does not start with a "o". Also, I do not think your code will even work because...

I don't see any "Brandon"s in there. Hope it helped!:smiley:


#3

@sk8terteen,
You are using the comparison
text[i] === "o" ( where "o" was meant to be the FIRST-letter of the =string Value= stored in the variable =myName= )
So either
change "o" into "B"
or
change "o" into myName[0] (which is the first-letter-of-myName )

=============================

if you target an Array-Element which is =undefined=
you will get an undefined as return-Value....

Using the code in your Original Post
the text-in |------| would be in your hits-Array ( i extended the text with u's which are the =undefined= )
( myName.length is 7 )

 blah blah Brandoblah blah blah Brando blah blah blah Brando
                |-----|              |-----|               |-----|
                1234567              1234567                uuuuuu

#4

Could anyone help? It works, but it comes out as 3, not my name
/*jshint multistr:true */

var text = "Hi, my name is Ian. How are you?";
var myName = "Ian";
var hits = [];

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


#5

You have to call "i" and "j" as a variable...

Also, in level 6/7, you are supposed to do an if statement. Please read those instructions and do it.