I'm confused why array of objects looped only returns one value (one for the truthy and one for the falsey) while using document methods (querySelector methods and getElement methods). Where as, I suppose to expect every object to return.
Here is the script:
let movies = [
{
title: "Spider-Man: No Way Home",
rating: 3.5,
hasWatched: true
},
{
title: "Unbroken",
rating: 5,
hasWatched: true
},
{
title: "Frozen 2",
rating: 5,
hasWatched: false
},
{
title: "Encanto",
rating: 5,
hasWatched: false
},
{
title: "Forrest Gump",
rating: 5,
hasWatched: true
}
];
printWatched = document.querySelector(".moviesWatched");
const printNotWatched = document.querySelector(".moviesNotWatched");
for (let i = 0; movies.length > i; i++) {
if(movies[i].hasWatched === true) {
printWatched.textContent = "You have watched " + '"' + movies[i].title + '"' + " - " + movies[i].rating + " stars";
} else {
printNotWatched.textContent = "You have not seen " + '"' + movies[i].title + '"' + " - " + movies[i].rating + " stars";
}
}
But, if I use document.write everything is nominal, working and returns every value inside of the array of objects...
let movies = [
{
title: "Spider-Man: No Way Home",
rating: 3.5,
hasWatched: true
},
{
title: "Unbroken",
rating: 5,
hasWatched: true
},
{
title: "Frozen 2",
rating: 5,
hasWatched: false
},
{
title: "Encanto",
rating: 5,
hasWatched: false
},
{
title: "Forrest Gump",
rating: 5,
hasWatched: true
}
];
const printWatched = document.querySelector(".moviesWatched");
const printNotWatched = document.querySelector(".moviesNotWatched");
for (let i = 0; movies.length > i; i++) {
if(movies[i].hasWatched === true) {
document.write("<p> You have watched " + '"' + movies[i].title + '"' + " - " + movies[i].rating + " stars <br> </p>");
} else {
document.write("<p>You have not seen " + '"' + movies[i].title + '"' + " - " + movies[i].rating + " stars <br> </p>");
}
}
Thank you guys for helping.
You are overwriting previous text with the last text. Create a variable and append all those string. Then at last use innerHTML
let movies = [{
title: "Spider-Man: No Way Home",
rating: 3.5,
hasWatched: true
},
{
title: "Unbroken",
rating: 5,
hasWatched: true
},
{
title: "Frozen 2",
rating: 5,
hasWatched: false
},
{
title: "Encanto",
rating: 5,
hasWatched: false
},
{
title: "Forrest Gump",
rating: 5,
hasWatched: true
}
];
const printWatched = document.querySelector(".moviesWatched");
const printNotWatched = document.querySelector(".moviesNotWatched");
let moviesWatched = '';
let moviesNotWatched = '';
for (let i = 0; movies.length > i; i++) {
if (movies[i].hasWatched) {
moviesWatched += `You have watched ${movies[i].title} - ${movies[i].rating} stars`;
} else {
moviesNotWatched += `You have not seen ${movies[i].title} - ${ movies[i].rating} stars /n`;
}
}
printWatched.innerHTML = moviesWatched;
printNotWatched.innerHTML = moviesNotWatched;
<div class='moviesWatched'></div>
<div class='moviesNotWatched'></div>