Your second "for" loop - Need Help


#1

-Link to Code-
https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661

It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable.
-That is the exact way the code isn't working-

//My code
 var text = "Hey, how are you \
doing? My name is link.";
var myName = "Link";
var hits = [];
if (text[i] === 'E') 
for(var i = 0; i < text.length; i++) {
var text = "Link";
var myName ="Link";
var hits =[Link];
if (text[i] === myName[0]){
for (var j = i; j < (i + myName.length); j++) {
hits.push(text[j]);
console.log(hits);
    }
  }
}   

// I don't understand what i'm doing wrong here?

#2

First of all variable text should has correct name, so if var myName = "Link"; text should has "Link", not "link".
Next problem is with if statement which should be inside for loop, because index i is not defined:

for(var i = 0; i < text.length; i++) {
   if (text[i] === 'E') { 
      // rest of your code 
   } 
}

But your if statement returns false because variable text does not have char like 'E'. This statement should return true, so should be:

if (text[i] === 'L') { ... }
// OR
if (text[i] === myName[0]) { ... }

Also you have redundant code, remove it please:

var text = "Hey, how are you \
doing? My name is Link.";
var myName = "Link";
var hits = [];
if (text[i] === 'E') // remove it
for(var i = 0; i < text.length; i++) {
var text = "Link"; // remove it
var myName ="Link"; // remove it
var hits =[Link]; // remove it
   if (text[i] === myName[0]){
      for (var j = i; j < (i + myName.length); j++) {
         hits.push(text[j]);
         console.log(hits); // replace it outside the for loop
    }
  }
}

#3

Hey, it seems i can't make my second for loop to add the item to the array. assuming the example above, shouldn't we just use the push method just whit the var "j"

hits.push(j);

?

tyvm in advance


#4

I got past it, thanks for the help.


#5

j is an index, so it's represents a number, and text[j] - is a character in current position of loop


#6

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