Im wondering why this code doesnt return year of a movie if i type it in. Am i missing something? Because using alert instead of return will give me No such a movie, No such a movie, No such a movie and then a year and then again No such a movie, basically a loop instead of doing it right away. Im using webtoolkitonline btw. However using return statement will only give me No such a movie.
var someArray = [
{
title: "A nice guy",
year: "1980",
},
{
title: "Batman",
year: "1985",
},
{
title: "Spiderman",
year: "1990",
},
{
title: "Love for lust",
year: "1999",
},
];
var input = prompt("What are you looking for?");
for (var i = 0; i < someArray.length; i++) {
myFunction();
}
function myFunction() {
if (input === someArray[i].title) {
return someArray[i].year;
} else {
return "No such a movie";
}
}
some part of you is very right – the variable i is defined in the scope of the for loop, but the function is created and run outside that. It has no knowledge of i.
Instead, put the content of the function within the for loop.
I use console.logs to track what’s going on with the variables in my code. It helps, like doing a console.log to track what the value of input is. You only want the code to run if input is not null (if the user has answered the prompt).
Here is an example of your code that will work:
var input = prompt("What are you looking for?");
var someArray = [
{
title: "A nice guy",
year: "1980",
},
{
title: "Batman",
year: "1985",
},
{
title: "Spiderman",
year: "1990",
},
{
title: "Love for lust",
year: "1999",
},
];
if (input !== null) {
var search = "No such movie";
console.log(input);
for (var i = 0; i < someArray.length; i++) {
if (input == someArray[i].title) {
search = someArray[i].year;
break;
} else {
search = "No such a movie";
}
}
console.log(search);
}