5. Your second "for" loop - Not sure understanding correctly


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661#


I am having trouble with this stage. Particularly the second 'for' statement.

In the first 'i','for' statement treats the text as an array, with each number relating to a whole word in the string (so text[1] would show 'man').

So in the second 'for' statement is the 'j' cycling through the text as though the individual words constituted the elements of an array still or does it treat the individual letters as elements of an array. It doesn't seem very clear from the instructions provided. I saw a comment on another thread which explained things much better, but still i don't feel clear about what is happening even if i can type something that looks vaguely logical.

Then, it says it will 'add characters to the array', but thinking of the whole code could it not run and find an 's', then add all the incidents of 's' to the array? Okay perhaps not as the .push is in the second 'for' section. I feel like this is on the tip of my brain but if anyone explain it clearly i would truly appreciate it.

This is my error statement, btw.

"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 = "The man Steven was Stan's friend, but Stan could help Mark with his voyage. Stan was lonely, but Stan couldn' remember the last time Steven called him Stan. Only Stannington or Stanley. Steven was a cad like that."
var myName = "Stan"
var hits = []

for (var i = 0; i > text.length; i++) {
    if (text[0] === myName[0]) {
        //second loop to push to final array//
        for ( var j = i; j < myName.length + j; j++) {
            hits.push(text[j]);
            }
        }
    };


#2

I am afraid i have already to correct you here. i will contain letters from the string stored in text, not whole words:

var text = "The man Steven was Stan's friend, but Stan could help Mark with his voyage. Stan was lonely, but Stan couldn' remember the last time Steven called him Stan. Only Stannington or Stanley. Steven was a cad like that."
var myName = "Stan"
var hits = []

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

your loop condition is also wrong, i=0 in the first iteration. which is smaller then the length of text, so the condition evaluates to false, the loop ends, so the loop made zero iterations

your if statement:

if (text[0] === myName[0])

is also wrong, the first letter of text is T, and the first letter of myName is S, in other words, this condition would always evaluate to false

First fix this problems first, then we can work on the second for loop later


#3

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