Estoy confundido por qué la matriz de objetos en bucle solo devuelve un valor (uno para la verdad y otro para la falsedad) al usar métodos de documento (métodos querySelector y métodos getElement). Donde como, supongo que espero que todos los objetos regresen.
Aquí está el guión:
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"; } }Pero, si uso document.write, todo es nominal, funciona y devuelve todos los valores dentro de la matriz de objetos...
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>"); } }Gracias chicos por ayudar.
Está sobrescribiendo el texto anterior con el último texto. Cree una variable y agregue todas esas cadenas. Luego, por fin, 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>