Web Analytics Made Easy -
StatCounter codecademy javascript search for your name exercise - CodingForum

Announcement

Collapse
No announcement yet.

codecademy javascript search for your name exercise

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • codecademy javascript search for your name exercise

    Hi folks. Can anybody please walk me through the the outer and inner for loop codes. Everything else makes sense except this part.

    Code:
    /*jshint multistr:true */
    
    var text="blah blah drew blah doug";
    var myName="drew";
    var hits=[];
    
    for(var i=0; i<text.length; i++){
        if(text[i]===myName[0]){
            for(var j=i; j<myName.length + i; j++){
                hits.push(text[j]);
            }
        }
    }
    if(hits.length===0){
        console.log("Your name wasn't found!");
    }else{
        console.log(hits);
    }
    My interpretation is this: the first for loop goes through each character in the text variable. And if it finds "d" letter, it starts the second for loop. This is where I break down. Why var j=i? What does this do? So for example, let's say the outer for loop i reached the 11th iteration (where the "d" is located), because the second for loop said var j=i, j is now 11? This so that the second for loop doesn't start at the beginning again, but rather start starts at 11th character? So then why j<myName.length + i?? Why not just j<myName.length? .Arghh, so confusing! Please explain like I'm 7 years old. New to js.

  • #2
    The code finds every word in the original text that starts with the same letter as your name and extracts as many letters from the front of that word as are contained in your name. So in this case it outputs ["d", "r", "e", "w", "d", "o", "u", "g"].

    j=i in order to start from the same position in the string in the second loop as you have already reached in the first loop. It needs to add i to the condition for the same reason it sets j to i in the first place - so as to ignore that many characters from the front of the string in the second loop.

    Without starting and ending the second loop i characters further from the start of the string it would always be processing the 'blah' on the front of the string instead of 'drew' and 'doug'.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

    Comment

    Working...
    X