I just can't figure out whats wrong with my code


#1

Would be very grateful if someone could tell me whats wrong with my code, thanks :smile:

/*jshint multistr:true */

var text = "dave kdfkdf dave kdfkdfffff dave";
var myName = "dave";
var hits = new Array();

var counter;
var nameCounter;

for (counter = 0; counter <= text.length; counter++){
    if (text[counter] === myName[0]) {
        for (nameCounter = counter; nameCounter < (nameCounter + myName.length); nameCounter++) {
            hits.push(text[nameCounter]);   
        }
    }
}

#2

Okay, i switched

nameCounter < (nameCounter + myName.length);

to

nameCounter < (counter + myName.length);

now it works, but could you explain why?

thanks :blush:


#3

In your code you made another variable called counter


#4

is this answer related to my first post?


#5

nameCounter < (counter + myName.length); --> this one works

nameCounter < (nameCounter + myName.length); --> this one does not

why?


#6

What is counter equal to?
What is nameCounter equal to?


#7

I don't think I did that lesson yet (I am doing JavaScript too).


#8

Just take a look at my first post


#9

That is all I see, so I don't see that they equal to any thing.


#10

there I initialize counter with 0


#11

Maybe because you put nameCounter equal to counter


#12

why does this cause problems here: nameCounter < (nameCounter + myName.length);? shouldn't nameCounter be equal to counter (0)?


#13

is nameCounter=counter; valid? I don't know. By the way, why would you want to do that?


#14

yeah it is. as long as nameCounter is smaller then nameCounter plus the length of the name I'm searching for, the for does push the strings from text into hits


#15

I just figured it out. nameCounter < (nameCounter + myName.length) will always return true.


#16

Great! I see that you figured it out.