Log it! Won't print name, only numbers


#1


I am doing the LogIt section of the search text for your name lesson. It tells me I have finished but prints off:
[ [ 17 ], [ 18 ], [ 19 ], [ 20 ] ]

/*jshint multistr:true */
var text = "Hey, how are you Jake."
var myName = "Jake"
var hits = []

for (var i = 0;i<= text.length; i++) {
    if (text[i]==="J") {
  for (var j=i; j < myName.length + i  ; j++) {
    hits.push([j])
    }
    if (hits.length === 0) {
        console.log ("my name wasn't found") }
        else { 
            console.log (hits)
        }}}


#2

why do you have this:

if (hits.length === 0) {
        console.log ("my name wasn't found") }
        else { 
            console.log (hits)

inside the for loop? the loop is to find your name, and then after the loop log the result?

The problem of the numbers is because you push numbers into the hits array. j is a number, which thanks to your for loop matches the indexes of your name in text

so you can do name[j] to convert the indexes to letters from your text string


#3

Now it prints out: [ undefined, undefined, undefined, undefined ]
I changed the placement of the }'s

/*jshint multistr:true */
var text = "Hey, how are you Jake."
var myName = "Jake"
var hits = []

for (var i = 0;i<= text.length; i++) {
if (text[i]==="J") {
for (var j=i; j < myName.length + i ; j++) {
hits.push(myName[j])
}}}
if (hits.length === 0) {
console.log ("my name wasn't found") }
else {
console.log (hits)
}


#4

j matches the indexes of the string in text, since the purpose of the second for loop is to find your name in text


#5

So I changed (myName[j]) to (text[j]) and it printed [ 'J', 'a', 'k', 'e' ]
What does the variable inside the hits.push() do?


#6

push() is a built in method to push things inside an array (hits is an array)


#7

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