5/7 - Need Help


#1

Hi all,

I am having a very hard time on this one - I have been trying to fiddle with this for 30 minutes and I finally need to ask for help. Can you please take a look at this and tell me what I'm doing wrong? Thank you so much!

/*jshint multistr:true */

text = "junk junk junk junk junk junk junk Cindy junk
junk junk Cindy junk junk Cindy junk junk junk junk junk junk junk";

var myName = "Cindy";

var hits = [];

for (var i = 0; i < text.length; i++)

if (text[i] === 'C')

{for (var j = i; j < (i+myName.length); i++)

hits.push(myName);}


#2

Hi, Cindy,

Couple of things a little amiss:

text = "junk junk junk junk junk junk junk Cindy junk
junk junk Cindy junk junk Cindy junk junk junk junk junk junk junk";

The above is multistr text (with a line break) which is illegal in JavaScript. The linter is set to watch for multi-line strings but we need to tell it where the line break is with an escape character, \, as in,

text = "junk junk junk junk junk junk junk Cindy junk \
junk junk Cindy junk junk Cindy junk junk junk junk junk junk junk";

Now with the help of jshint, JavaScript sees a complete string primitive, as expected.

The other error is the missing code blocks on the for statements:

for (...) {
    if (...) {
        for (...) {
            hits.push(text[j]);
        }
    }
}

Also, the inner loop should be incrementing j, not i, and you see above that we are pushing one letter to the hits array, per iteration of the inner loop.


#3

I can tell you that one thing that you did wrong was that you declared your variable of "i" but then called a non-existant variable, "j" in the following code

{for (var j = i; j < (i+myName.length); i++)


#4

You know, I was wondering about the jshint concept, thank you for that! I thought it was too long but since they didn't say to use it in the tutorial yet I didn't. I fixed that. Now when you wrote, "the other error is the missing code blocks on the for statements," what do you mean by code blocks? I noticed you have the 4 lines indented each, is this what you mean? Because I have code on those 4 lines. I want to get the lingo right. Thank you so much!! I also fixed the j inside the inner loop, I should have caught that.


#5

I thought we were supposed to use j in the second for loop? I am completely lost now.


#6

Yes, we need j in the inner loop, so long as we remember to increment it, and not i in that loop.

This is an object literal, { key: value } and this,

{ // code statement }

is a code block. They are common and in some cases a requirement.

function() {}
var foo = function (bar) {};
for (var i = ... ) {}
if () {} else if () {} else {}
do {} while ();
while () {}
switch () {}

The earlier example illustrates how nesting is indicated by indentation to help us visualize the structure.