What's wrong with my code? (Your second "for" loop) [Resolved]


#1

My code...

/*jshint multistr:true */

var text = "cheese, cheese, Chicken, cheese, cheese, \
cheese, cheese, cheese, Chicken";
var myName = "Chicken";
var hits = [];

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

I think I made my second for loop wrong.

Ps. Don't just give me the answer, please explain it to me.

[New code]
"The main problem was I added parentheses to> myName.length+i."

/*jshint multistr:true */

var text = "four, four, Chicken, four, four \
four, four, four, Chicken, four, four, Chicken";

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

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

}

}


#2

Hello @nerdcommander,

Unfortunately your mistake resides in your first for loop.

for(var i=0; i if(text[i] === "C") {

For-Loops have 4 parts that are absolutely necessary for them to work.

for ( initialization , condition , increment/decrement/"PostFix" ) { /*Code*/ }

So change your first for loop to have the condition increment until it reaches the end of the text. or "text.length"

If you need any help with how to do that let me know and I'll help you out in more depth.


#3

Yeah, could you please explain in more depth?


#4

Well you already have the other For-Loop as it should be:

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

for( initialization ; condition ; "PostFix" ){ ... }
  • Initialization, Where you create a variable to use in your for loop: var j = i
  • Condition, As long as the condition is true the code will run: j < (myName.length + i)
  • PostFix, how the for loop increments or decrements itself after every time it runs it's code: j++

So you'll need to do that for your first For-Loop as well.

for (var i = 0 ; condition ; PostFix ) {

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

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

So you just need to add in the condition and how the for loop will increment or decrement.


#5

I still can't figure out what's wrong...sigh

/*jshint multistr:true */

var text = "cheese cheese Chicken cheese cheese \
cheese cheese cheese Chicken";
var myName = "Chicken";
var hits = [];

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


#6

for(var i = 0; i if(text[i] === "C") {

Again right there is your problem, this line cannot work.

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

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

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

If you need a refresher on how For-Loops work, please see here.


#7

Thank you!:grinning: