Paze
Paze

Reputation: 183

Code won't find my name

var text = "Hue, bla, hue, rhr, aek kmggg mlsd k Bjarni sdkrals fn lol Bjarni\
lelelele Bjarni";
var myName = "Bjarni";
var hits = [];
for(var i = 0; i < text.length; i++); {
    if (text[i] === "B"); {

        for(var j = i; j < (myName.length+i); j++) {
            hits.push(text[j]);
        }
    }
}
console.log(hits);

This is supposed to return my name, but it just returns an array containing a few undefined values.

Upvotes: 0

Views: 128

Answers (2)

LarryFisherman
LarryFisherman

Reputation: 322

You've just got a few syntactical errors and a missing break statement to fix. This should work:

var text = "Hue, bla, hue, rhr, aek kmggg mlsd k Bjarni sdkrals fn lol Bjarni\ lelelele Bjarni";
var myName = "Bjarni";
var hits = [];
for(var i = 0; i < text.length; i++) {
    if (text[i] === "B") {

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

    break;
    }
}
console.log(hits);

To clarify; you had a semicolon after the line if( text[i] === "B");, another semicolon after your first for loop and you were missing a break statement, so it would've looped around throughout the entire "text" string, which may or may not have been unintentional behaviour.

Upvotes: 0

Pointy
Pointy

Reputation: 413682

The problem is here:

if (text[i] === "B"); {

Get rid of the semicolon. The semicolon in that point of the code makes it like:

if (text[i] === "B")
  ; // DO NOTHING AT ALL

{ // START A BLOCK
    for(var j = i; j < (myName.length+i); j++) {
        hits.push(text[j]);
    }
}

edit — oh and there's another one (with similar effects) after the for loop header. It should be:

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

Upvotes: 2

Related Questions