Output doesn't seem right


#1

https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/6?curriculum_id=506324b3a7dffd00020bf661#


no error messages


/*jshint multistr:true */
var text = "jdkal;dskjs Furat ;lsadkjakjsd Furat";
var myName = "Furat";
var hits = []
for (i = 0; i <= text.length; i++){
    if (text[i] === myName[0]){
        for (var j = i; j <= (myName.length + i); j++){
            hits.push (text[i]);
        }
    }
}
if (hits.length === 0){
    console.log("Your name wasn't found!")
}
else{
    console.log(hits)
}

So my problem is my output, it just prints out [ 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' ]
I can't find the problem and now I feel stupid :confused:


#2

Hi,

There are some logical errors in your code.
First for loop should be like this: for (i = 0; i < text.length; i++)
And the second for loop should be like this: for (var j = i; j < (myName.length + i); j++)
In your second for loop you are pushing text[i] to the hits array. That's why the output prints out [ 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' ]

You have to push text[j] to hits array. Then it would give you the desired output.
And also put semicolons at the end of the statements shown below:

var hits = [];

console.log("Your name wasn't found!");

console.log("Your name wasn't found!");

#3

/*jshint multistr:true */
var text = "jdkal;dskjs Furat ;lsadkjakjsd Furat";
var myName = "Furat";
var hits = []
for (var i = 0; i <= text.length; i++){
if (text[i] === myName[0]){
for (var j = i; j <= (myName.length + i); j++){
hits.push (text[j]);<----the only problem with your code is that you forgot to change. test[ j ]
}
}
}
if (hits.length === 0){
console.log("Your name wasn't found!")
}
else{
console.log(hits)
}


#4

Thanks, that solved my problem.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.