How do I keep my code from looping forever?


#1


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


My code allows me to "pass" the exercise but I'm pretty sure I would not want my program to loop for infinity giving me the same output over and over. I want it to print my name once and once only. Any ideas?


/*jshint multistr:true */
var text = "This is a string full of words that Kyle wrote.\
Kyle likes to write longs sentences." 

var myName= "Kyle" 

var hits= []

for (var i = 0; i< text.length; i ++){
    if (text[i] === "K"){ 
        for ( var q = i; q < i + myName.length; q ++){
        hits.push(text[q]); 
        }
    }
console.log(hits)}


#2

The above are not incrementing. Remove the space from both expressions.


#3

So I removed the spaces between those variables i & q.
After that I also changed the end at
{
console.log(hits) }

to

{
console.log(hits[q])}

and I was able t get it to print a single line of "undefined" but still not my name...

var text = "This is a string full of words that Kyle wrote.\
Kyle likes to write longs sentences."

var myName= "Kyle"

var hits= []

for (var i = 0; i< text.length; i++){
if (text[i] === "K"){
for ( var q = i; q < i + myName.length; q++){
hits.push(text[q]);
}
}
console.log(hits[q])}


#4

The hits array is not tied to the controls i or q, so cannot be reliably accessed using those indexes. The ideal situation would be to wait until the loop is finished and log the final array.

for ( ... ) {

}
console.log(hits);    // [ 'K', 'y', 'l', 'e', 'K', 'y', 'l', 'e' ]

#5

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