Having issues with second For Loop


#1

I am sure I got everything right but I keep on coming across this error that says:

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.

From what it tells me I am misusing the push function for the hits array, but I can not see how I am doing anything wrong, I will include my code.

/*jshint multistr:true */

var text = "etc etc etc Daniel etc etc etc";

var myName = "Daniel";

var hits = [];

for(var i = 0; i >= text.length; i++)
{

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

}

Again I can not see anything wrong with the code or how I used the push function, if anyone can help or explain something I would really appreciate it.


#2

for(var i = 0; i >= text.length; i++)

should be

for(var i = 0; i < text.length; i++)

having the check with i being greater than text.length would mean your for loop iterates 0 times


#3

you put i++ try j++ at the end of your for statement


#4

Must be

for(var i = 0; i <= text.length; i++)

Cause zero indexing means if we count from zero length could be == i

And if you dont count var j up it doenst can work

for(var j = i; j <= (i+ myName.length); i++)

This makes a infinite loop


#5

Sorry I didn't see that, I was sure I used J++ but I guess I must have accidentally typed i by a reflex.


#6

Sorry that is a little embarrassing, I should have caught that, thanks a lot.


#7

I disagree.

Running the for loop here on a text.length being <= instead of just < will result in 1 extra loop that you may have not intended.

The character endstring \0 is something that I find people don't wish to iterate on.

Using < instead of <= will iterate over every character within a text.

e.g., See the following script, run it in any browser / jsfiddle of your choice.

<html>
    <script type='text/javascript'>
        var foo = "test";
        for(var i = 0; i <= foo.length; i++)
        {
            document.write(foo.charAt(i));
            document.write("-" + i + "<br>");
            
        }
        
        document.write("<br>");
        document.write("<br>");
        
        for(var i = 0; i < foo.length; i++)
        {
            document.write(foo.charAt(i));
            document.write("-" + i + "<br>");
            
        }
    </script>
</html>

#8

I`m sorry you did it totally right my fault.


#9

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