When I run the very simple following code, for some reason I get the following result in the browser console: "6 You have not watched undefined undefined." Can anyone point out my error please?
var movies = [{
title: "The Mummy",
hasWatched: true,
stars: "5 stars"
},
{
title: "About A Boy",
hasWatched: true,
stars: "5 stars"
},
{
title: "It",
hasWatched: false,
stars: "5 stars"
},
{
title: "Cleopatra",
hasWatched: false,
stars: "5 stars"
}
];
for (var i = 0; i <= movies.length; i++) {
if (movies.hasWatched) {
console.log("You have watched " + movies.title + " " + movies.stars + ".");
} else {
console.log("You have not watched " + movies.title + " " + movies.stars + ".");
}
}
3 Answers 3
You have an array of objects so you need to reference the index of each array element. You also need to reduce your loop by one since array indexes are zero-based but the length is not.
var movies = [{
title: "The Mummy",
hasWatched: true,
stars: "5 stars"
},
{
title: "About A Boy",
hasWatched: true,
stars: "5 stars"
},
{
title: "It",
hasWatched: false,
stars: "5 stars"
},
{
title: "Cleopatra",
hasWatched: false,
stars: "5 stars"
}
];
for (var i = 0; i < movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
Comments
Change the for condition to i < movies.length; you have one extra iteration.
And you also need to references movies[i] to get the actual movie, for example, movies[i].title.
In the above example, the last index is 3 (items are numbered 0, 1, 2, 3), but your loop is going until 4 and will attempt to find movies[4].title and return undefined.
Comments
for (var i = 0; i <= movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
you were just missing the index identifier while accessing
moviesis an array. You need to index it withi. Iemovies[i].hasWatched