Understanding what's happening in Your Second For Loop


#1


Okay, I'm trying to truly understand what's going on in this code. I need some help, let me know if I got the gist of it.

The first loop has i = 0, i is less than the text length so this passes on to the if statement, if the text area is 0 (which is i) equals T then we run the next loop?

(This is where I lose it totally) Now that loop for when the first letter hits T, we make j = i(T) or does j = i(0)? j (0) is less than namelength + T(whose position on the array is 0 correct?) it then pushes(myName) and adds j 1 to j. so now j(2) = i(0)? j is less than name length, push out myName then add another j? How does this write out myName to be Tbone?
Can somebody break this down for me please

Sorry if my description is confusing or difficult to understand


/*jshint multistr:true */
var text = "Hello, my name is Tbone. Tbone is too cool, \
yay for Tbone.";
var myName = "Tbone";
var hits = [];

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


#2

Whenever "T" (or better yet, the first character of myName) is encountered, push the next myName.length characters to the array.


#3

I guess I'm not understanding how .push works


#4

> a = []
> console.log(a)
[]
> a.push(1)
> console.log(a)
[ 1 ]

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push


#5

Aw man that was easy lol.
Okay I understand that simple one there, now what I'm trying to understand is why is the code

hits.push(myName)

if no where in the code block of the loop or if statement am I using the variable hits?


#6

You are, in that line.


#7

Okay I think I got it, I went on to the next lesson and then it says to print hits. I was confused because that line of code with hits was sort of just there

Thank you for helping out and being patient with me


#8

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