5.Your second "for" loop


#1



I can't understand .push process. I put in 'hi' and it worked.
hits.push('hi');

But the correct answer that I found was
hits.push(text[j]);

How this process works? and why the answer is text[j]?


*jshint multistr:true */
var text = "He is rob. rob did well in the battle. \
Everybody scared rob.";
var myName = "rob";
var hits = [];

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


#2

In your first loop runs until $i is smaller or has the same value as text.length

var text = "He is rob. rob did well in the battle. \
Everybody scared rob.";
var myName = "rob";
var hits = [];

// First loop until i is <= text.lenght 
for (var i = 0; i <= text.length; i++) {
    // if value text[i] is "r" go into statement and run the second loop
    if (text[i] === myName[0]) {
        // now we know the Position from the first letter of myName it is "i" text[6]
        // we dont count "i" up because it could be we found the name a second time  
        // var j = i
        // we know the length of name  so the Loop runs only until j<=myName.lenght (3times)
        for (var j = i; j <= myName.length + i; j++) {
            // now the Magic ;) 
            // you wanna push the letter from your Name into the Array. 
            // Rember j = i  and you Count j up every round 
            // myName Begins on text[6] and know you push it into the Array 
            hits.push(text[j]);// text[6] is "r" -- next round j++ count j up to 7 -- text[7] is "o" -- next round j++ count j up to 8 -- text[8] is "b" 
            }
        };
    }

#3

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