Reputation: 347
can someone explain why I am getting undefined in my loop? I am trying to run a loop that lets me know if its true if i've watched something as well as the rating. What am I doing wrong?
var films = [
{
movie: "fast and the furious",
rating: 4,
seen: true
},
{
movie:"13 reasons why",
rating: 5,
seen: true
},
{
movie:"beaty and the beast",
rating: 4,
seen: false
}
];
films.forEach(function(movie){
var result = "You have ";
if(movie.seen) {
result += "watched ";
}
else{
result += "not seen ";
}
result += "\"" + films.movie + "\" - ";
result += films.rating + " stars";
console.log(result);
});
Upvotes: 1
Views: 645
Reputation: 10675
var films = [
{
movie: "fast and the furious",
rating: 4,
seen: true
},
{
movie:"13 reasons why",
rating: 5,
seen: true
},
{
movie:"beaty and the beast",
rating: 4,
seen: false
}
];
films.forEach(function(film){
var result = "You have ";
if(film.seen) {
result += "watched ";
}
else{
result += "not seen ";
}
result += "\"" + film.movie + "\" - ";
result += film.rating + " stars";
console.log(result);
});
Use some other variable to enter foreach
and use same variable to read properties.
Upvotes: 0
Reputation: 763
You passing a movie parameter in your function. you should use this for result.
var films = [
{
movie: "fast and the furious",
rating: 4,
seen: true
},
{
movie:"13 reasons why",
rating: 5,
seen: true
},
{
movie:"beaty and the beast",
rating: 4,
seen: false
}
];
films.forEach(function(movie){
var result = "You have ";
if(movie.seen==true) {
result += "watched ";
}else{
result += "not seen ";
}
result += "\"" + movie.movie + "\" - ";
result += movie.rating + " stars";
console.log(result);
});
Upvotes: 0
Reputation: 2230
You should access the element, not the array, in your iterator function:
films.forEach(function(movie) {
var result = "You have ";
if (movie.seen) {
result += "watched ";
} else {
result += "not seen ";
}
result += "\"" + movie.movie + "\" - ";
result += movie.rating + " stars";
});
Upvotes: 1