What's Wrong With My Code?


#1

var text = "My name is Chloe. I've been asked to come up with some text including my name, which is Chloe.";
var myName = "Chloe";
var hits = [];
for (var i = 0; i < text.length; i++)
{ if (text[i] === 'C') {
for(var j = i; j < i + 5; j++)
newArray = [];
newArray.push('C');
newArray[0];
}
}

Apparently the second for loop isn't ending in the correct place, what's the problem?


#2

Try this one:

var text = "I'm Nick, I like to be called Nick, everybody likes\ Nick";
var myName = "Nick";
var hits = [];
for (var i = 0; i < text.length; i++){
    if (text[i] === "N"){
        for (j = i; j < (myName.length + i); j++){
            hits.push(text[j]);
        }
    }
}

#3

Thanks, I figured it out


#4

var text = "My name is Chloe. I've been asked to come up with some text including my name, which is Chloe.";
var myName = "Chloe";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === 'C') {                                // until here, everything is correct
for (var j = i; j < i + 5; j++)                    // in this loop, we are trying to say "from C (var j = i => start at i),                                                             push x_number of letter after it (j < (myName.length + i)) in the array                                                             hits ( hits.push(text[j]); )
newArray = [];                                     // Idk what you re try to do here but you dont need to create a new empty array since you already did at the beginning (var hits = []; ). Also -first- if you want to create a variable you need to say var newArray. And -second- you shouldn t create an empty array in a loop cs it will be recreate every time it goes through the loop. To store value, you always have to create your array outside the loop.

And you forget to close your second for loop.

There you go, hope it helps you :smile:


#5

My biggest problem was that I forgot I'd already declared an array - oops. It's all solved now but thank you for the help!


#6

n/p :wink: