5. Another way to think about the second loop


#1


5. Your second loop


My solution was slightly different and wanted to share and see if there is any issue/chunkiness to it.

The value of the first loops incrementer 'i' stays the same in the second loop. I then only want to loop through the length of 'myName' and push into 'hits' where 'i' had left off plus where 'j' is at its current index or hits.push(text[i+j]);


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


#2

What logged to the console for the hits array?


#3

I tried @neeziv's solution:

var text = "af grwg rh thrthj jjy jtj Denys g er Denys";
var myName = "Denys";
var hits = [];

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

Result:

Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.

I don't understand this warning. In console I have:

["D", "e", "n", "y", "s", "D", "e", "n", "y", "s"]

#4

I would try and refresh the page. The first time I ran it I got the same error message. I think the grader is looking for the

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

solution


#5

Console logs.

[ 'R', 'a', 'y', 'R', 'a', 'y', 'R', 'a', 'y' ]

Say that the first for loop and if statement finds the first 'R' at index 5. This second loop starts with j at 0 and when it goes to push into hits the first time it will be adding index 5 + 0, then 5+1, then 5+ 2. Then when it breaks the condition it jumps out of the second loop back to the first loop at index 6 and forward until it finds another 'R'. Or at least that was my thinking.


#6

Without seeing all of your code, I cannot tell what exactly is happening. :slight_smile:


#7

:slight_smile:

var text ="I can see the coming Ray of the glory of the \
Ray, and it has seen Ray coming from the stars";

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

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

#8

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