*edited* My while loop solution works, but my for loop solution needs help


#1


https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/7?curriculum_id=506324b3a7dffd00020bf661


Hello,
I tried this exercise initially with a for loop and I couldn't get it to work. Then I switched over to a while loop and it did exactly what I wanted it to- find and report the index position where 'henry' shows up. Here's the code that works:


/*jshint multistr:true */
//Text I'm searching
var text = 'aa henry kasjd;fj henry df';
//Search query
var myName = 'henry';
//An array to store the index numbers of the search string
var hits = [];
var searchString = text.indexOf('henry');
/*
Strategy:
use indexOf() to search for the string in question
push the index location into hit
then run indexOf() again, starting from the index position of the last hit
*/
while (searchString !== -1) {
    hits.push(searchString);
	searchString = text.indexOf('henry', searchString + 1);
}
if (hits.length === 0) {
    console.log("Your name wasn't found!");
}

console.log("\'henry\' was found at position " + hits.join());

For the sake of completion, I'd like to be able to do the same thing with a for loop. For whatever reason, my loop isn't looping- it finds the first instance of 'henry', then stops there without finding the others. Can you help? Thanks.

/*jshint multistr:true */
//Search subject
var text = 'aa henry kasjd;fj henry df';
//Search query
var myName = 'henry';
//An array to store the index numbers of the search string
var hits = [];

/*
use indexOf() to search for the string in question
store the index location into hit
then run indexOf() again, starting from the index position of the last hit
*/
if (text.indexOf('henry') !== -1) {
    hits.push( text.indexOf('henry') );
    for (var i=hits[hits.length -1] ; i<text.length; i++ ) {
        if (text.indexOf('henry')!== -1) {
            hits.push(text.indexOf('henry') );
        }
     }
} else {
    console.log("Your name wasn't found!");
}

console.log("\'henry\' was found at position " + hits.join());

#2

Please, post your for loop solution.


#3

Hi,

I apologize for not being clear. The first code block is my working while loop solution. The second code block is the for loop solution I'd appreciate some help with.


#4

don't use a for loop, with the code you have this make no sense.


#5

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