Exercise said I passed but I got a number as result. Is it right? - Exercise 5. Your second "for" loop


#1

Hi, guys!

It's me. Again. :slight_smile:

I inputted the following code but instead of returning the letters inside my name, I received a "28" result (which is the count on all the letters that should appear).

What did I do wrong?

I received no error for this exercise but I think I did something wrong.

/*jshint multistr:true */
var text = "hahdasiudhasdasdas vanessa asdasd asdasd vanessa asdasdvanessa asdasdads vanessaasd";
var myName ="vanessa";
var hits = [];

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

Thanks for all the support!


#2

Your first for loop

Add the keyword var before i = 0.

Your if statement

Your supposed to check for the first letter of the string you are trying to find so in this case your code wouuld be
if (text[i] === "v")

Your second for loop

You don't need the parentheses before myName.length and you dont need to add it to i here myName.length + i

That's all you need to do. :slight_smile:


#3

@bandit , thanks for your reply!

OK, adding the var statement worked! :tada:

Should't myName[0] be the same as "v"?

1) Parentheses: OK
2) Regarding the i variable, if I don't sum it to my name length when I get the next position it will sometime count my stop condition wrong, wouldn't it?
eg.: the fourth lookup under

A) With the + i, the j loop stop condition would stop under the 7+74th character (that would be "a"):

for (i=74; i<83; i++) {
    if (text[74] === "v") {
        for (j=i; j < (7 + 74); j++) {
            hits.push(text[j]);
        };
    };
};

B) Without the + i, the j loop stop condition would stop under the 7th character (that would be "i"):

for (i=74; i<83; i++) {
    if (text[74] === "v") {
        for (j=i; j < (7); j++) {
            hits.push(text[j]);
        };
    };
};

#4

Why this isnt the same is because you are trying to access a string the way you would access a list.


#5

No the reason you don't need = i is because you increment the loop by adding the second loop which actually points to your text. The loop will stop when all letters have been pushed to the empty list. hits = []


#6

@bandit, thanks for your reply!

I discovered a website to test JS syntax and my code worked inside that: https://jsfiddle.net/

So I think the code is ok, maybe just some configuration made for Code Academy platform resulted on a number output.

Regarding the piece of code below, doesn't seem that, if I leave the i variable out, my stop condition wouldn't let my code run, as j=74 is greater than 7 (stop condition: j < 7)?

Please see code output below:

If I remove the i variable, it returns no value: