This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Carl
about 9 years

The Eric example

The text on the left says:

Now, as we mentioned, this system isn’t perfect. For instance, if the paragraph contains both “Eric” and “Eddie”, we’ll see this in our hits array:

[‘E’,’r’,’i’,’c’,’E’,’d’,’d’,’i’,’e’];

I expect the array would look like: [‘E’,’r’,’i’,’c’,’E’,’d’,’d’,’i’], without the last letter of Eddie. Since each time the capital ‘E’ is found, four letters (length of ‘Eric’) are copied to the array. What is going on?

Answer 5517f2d8d3292fe79a0031b0

1 vote

Permalink

same output:

[ 'E', 'r', 'i', 'c', 'E', 'd', 'd', 'i' ]

code:

var text = " Eric and Eddie"
var myName = "Eric"
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])
        }
    }    
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}
points
Submitted by tra201
almost 9 years

Answer 55b104cae39efe27930007b2

0 votes

Permalink

It’s silly how this little mistakes can get us really confused as at this stage we are all learning.

Someone should correct that.

myName.length in Eric’s case = 4 myName.length in Eddie’s case = 5

So as Carl and tra201 suggest, the result would not be [‘E’,’r’,’i’,’c’,’E’,’d’,’d’,’i’,’e’] but [‘E’,’r’,’i’,’c’,’E’,’d’,’d’,’i’]

I am happy I found this post as I was starting to get crazy and very frustrated thinking that I wasn’t able to understand it.

points
Submitted by Bernardo San Juan
over 8 years