Part 5 help


#1

Im not sure about what they are asking me to do, so here is my code untouched from the last lesson

/*jshint multistr:true */
var text = "Hey I am John Egbert. I am in Homestuck. John is a good name.";
var myName = "John";
var hits = [];
for (var i = 0; i <= text.length; i += 1) {
if (text[i] === "J") {

}

};

what do i do?


#2

The first match for 'J' in the text string will be at index 9. We know that John is 4 characters long, so must be at index 9, 10, 11, and 12. Our inner loop will need to iterate over those indices, and append each character to the hits array.

We'll start by initializing the inner loop iterator to equal the current index, i. From that index we will then step our way through the name.

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

The lesson text discusses what push() does. The above is appending one letter at a time to the array. After the first match, and running of the inner loop, hits will look like this...

   [ 'J', 'o', 'h', 'n' ]

#3

okay so i think i would get the lesson, but like i dont really know any of the vocabulary
also, why is j = 1
and where did j come from


#4

j is equal to i, not 1. We need to declare a new variable in the inner loop so we don't lose our position in the outer loop. It is common for programmers to use i, j, k for loop iterator variables.

An iterator variable is also called an index, especially when iterating over (cycling through) a string or array. Their characters/elements are each given an index.


#5

sorry but what is an index


#6

An index is anything that we can write as a subscript to indicate a position in a string or array.

myName[0]

is the first letter of your name, J. It is at position index 0 of the string, o is at index 1, 'h' is at index 2, and n is at index 3.

myName[0] === 'J'
myName[1] === 'o'
myName[2] === 'h'
myName[3] === 'n'

just as,

text[9] === 'J'
text[10] === 'o'
text[11] === 'h'
text[12] === 'n'

The value in the brackets, [ and ] is the index.


#7

okay now i get it thanks :smile: