I Don't Understand What the Console is Producing With This Code?


#1

I have the code correct for this, but I don't understand how it relates to what the console reads out ("20")....

Please advise....

Correct Code Is:

/*jshint multistr:true */
var text = "My name is Matt and I'm 37 years old. My name Matt came from Matt hew.";

var myName = "Matt";

var hits = []

for(var i = 0; i < text.length; i++) {
if (text[i] === 'M') {
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
};


#2

Hey @mattjacobnyc,

Mine works well. Look:

    var text = "blob blob blob Ryan blob blob Ryan blob blob blob blob blob blob blob blob Ryan blob";
    var myName = "Ryan";
    var hits = [];
    
    for (var i = 0; i <= text.length; i++) {
        if(text[i] === "R"){
            for (var l = i; l < (i+myName.length); l++) {
                hits.push(text[l]);
            }
        }
    }

And the output is 12.


Now I tried this out:

var text = "blob blob blob Ryan blob blob Ryan blob blob blob blob blob blob blob blob Ryan blob R";
var myName = "Ryan";
var hits = [];

for (var i = 0; i <= text.length; i++) {
    if(text[i] === "R"){
        for (var l = i; l < (i+myName.length); l++) {
            hits.push(text[l]);
        }
    }
}

If you look at my two variables 'text', you'll see that there's an extra 'R'. That 'R' made the output as 16, not 12.

So my guess:

There are three Matts.

"Matt" has 4 letters.

3 times 4 = 12

My has a capitalized letter of M.

How many Ms:

2M:

var text = "My name is Matt and I'm 37 years old. My name Matt came from Matt hew.";

Now, since there's four letters in Matt, the code will put the capitalized Ms as four letters.

2Ms + 3Matts = 5 times 4 = 20

I think it's like that. :smiley:


#3

@mattjacobnyc, @ragezapper makes some good points. Now I want you to try this.
Add these statements to your code and run it

console.log(hits);
console.log("The length of my hits array is "+hits.length);

that 20 is just the number of characters that were pushed to the hits array


#4

a few questions:
- why do we need to input this empty var hits = [];?
- I run my below code but how come it shows that only 1 character was pushed to the hits array instead of 14 characters (in var text containing the name Rasheed 2 times)

   var text = "When you rock with Rasheed, you go hard with Rasheed.";

    var myName = "Rasheed";

    for (var i = 0; i < text.length; i++) {
        if (text[i] === "R") {
            for (var j = i; j < (myName.length + i); j++) {
                var hits = [];
                hits.push (text [i]);}
        }
        }

#5

everything inside this for loop will be executed the number of times the for loop runs but in your code each time you push a character to hits, when the for loop comes back inside you override hits and set it to an empty list. Hence only one element can be pushed in there