Out of memory error? second loop exercise


#1

Hi Guys, I am new here and learning how to code.
I have started the second loop exercise, but it gives me this error: out of memory... I guess my code causes this... can someone help me?
my code:

/*jshint multistr:true */

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

where is the problem? I have checked all and it looks fine to me...


#2

in your code the error lies here

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

you wrote i++ but it should be j++ hence j will always be equal to i so the loop will run continuously
Here it is corrected

// here using '\' as an escapement is bad rather you
// should use the concat operator "+"
var text = "Hey, how are you "+
"doing? My name is Emily. "+
"where are you Emily? "+
"should I call you Emily?";
var myName = "Emily";
var hits = [];
for (var i = 0; i < text.length; i++) { 
   if (text[i] === 'E'){
       for ( var j = i; j < myName.length+i ; j++ ){
           hits.push(text[j]);
           }
       }
       
}
console.log(hits);

you can also try this

// here using '\' as an escapement is bad rather you
// should use the concat operator "+"
var text = "Hey, how are you "+
"doing? My name is Emily. "+
"where are you Emily? "+
"should I call you Emily?";
var myName = "Emily";
var hits = [];
for (var i = 0; i < text.length; i++) { 
   if (text[i] === 'E'){
       //what i am doing here is that
       // if you find an 'E', then look ahead
       //exactly 4 away from your current position
       //if,together with the E matchesmy entire name
       // then push to hits
       var found = text[i]+text.substring(i+1, i+myName.length);
       
       //debugging statement
       console.log(found);
       
       if(found === myName)
           hits.push(found);
       }
       
}
console.log(hits);//[ 'Emily', 'Emily', 'Emily' ]

Click here to labs


#3

I have found some errors in my script and corrected them. corrected code here:

/*jshint multistr:true */

var text = "Hey, how are you \
doing? My name is Emily. \
where are you Emily? \
should I call you Emily?";
var myName = "Emily";
var hits = [];
for (var i = 0; i < text.length; i++) { 
   if (text[i] === "E") { // E in quotes
       for (var j = i; j < (myName.length + i); j++ ){// missing var before j, and j++ instead i++
           hits.push(text[j]);
           }
       }
       
}

EDIT: WORKING NOW!!!!