5,6,7/7 Apparently the code is good, but there is no text displayed in console


#1

Hello,

If someone could look a bit at my code and tell/ explain me :

  • At 5/7, I have this code :

var text = "bsvsdf Ioana Ioana fdfsfsdfc dffsff Ioana sdsafad";
var myName = "Ioana";
var hits = [];
for (var i=0; i < text.length; i++){
if(text[i]==="I"){
for(var j=i; j < i+myName.length;j++){
hits.push(text[j]);
}
}
}

Which apparently is good, but in the console only "15" is displayed (which is, probably, the total number of letters in my name => Ioana - 5 letters * 3) and I don't know why.

  • At 6/7 , I have the above code + :

if(hits.length = 0){
console.log("Your name wasn't found!");}
else {
console.log(hits);}

Which seems correct again(The "Way to go text appears") but only "[ ]" is displayed in the console. (the hits variable is empty, maybe?)

and at 7/7 it seems correct again, but nothing is displayed in the console.

I looked today a lot at my code and tried to figure out what's happening but still didn't find the solution...
Thank you in advance to whom has some time.


#2

var text = "bsvsdf Ioana Ioana fdfsfsdfc dffsff Ioana sdsafad";
var myName = "Ioana";
var hits = [];
for (var i=0; i < text.length; i++){
if(text[i]==="I"){
for(var j=i; j <( i+myName.length);j++){
hits.push(text[j]);
}
}
}
if(hits.length === 0){
console.log("Your name wasn't found!");}
else {
console.log(hits);
}

Your if statement says

if(hits.length === 0) or if(hits.length == 0)

I checked with 5/7, and only the number is displayed, so you're fine there.
And when i used

 if(hits.length = 0)

It shows up as []. FYI, [=] is used to assign, whereas [==/===] is used to compare.
Hope I could help!


#3

I just wanted to mention that I was stuck trying to figure this out as well. The console would either produce a larger number than the length of myName or it would produce [], but it would never scan and give me my name in the console. With everything looking great, I still didn't understand. Sure enough, it was that damned "=" to "===" problem. Thanks a bunch!

I later found out it produced the number 8 because my 4-letter name is in there twice. Dumb me!

Here was my code before the "===" change in the last if statement for reference:

/*jshint multistr:true */

var text = "Cary and omg wtf Cary so much crap";
var myName = "Cary";
var hits = [];

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

if(hits.length = 0) {
console.log("Your name wasn't found!");
}
else
{console.log(hits)};