as part of a code along for a Udemy Web Development Bootcamp (by Colt Steele), I have the following javascript that simply lists items within an array, changing the console.log text depending on a boolean "hasWatched" condition.
Despite copying the code-along character for character after my own attempt, the console.log always returns the array items as true, regardless of whether I try this within a standard for loop, or a forEach loop. I've posted my code below. The script is connected to an html file that has nothing beyond a boiler plate, script link and title.
console.log("Script Connected")
// Create an array of objects. Each movie should have a title, rating and hasWatched properties. Iterate through the array and print out results and whether it has been hasWatched
var movieArr = [
{
title: "LOTR",
rating: 5,
hasWatched: true
},
{
title: "Fast and the Furious",
hasWatched: false,
rating: 1
},
{
title: "Let the Right One In",
rating: 5,
hasWatched: false
}
]
//first attempt
for(i = 0; i < movieArr.length; i++){
if(movieArr[i].hasWatched = true){
console.log("You have seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
} else {
console.log("You have not seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
}
}
//second attempt
movieArr.forEach(function(i){
var result = "You have ";
if(i.hasWatched){
result += "watched ";
} else {
result += "have not watched ";
}
result += "\"" + i.title + "\" - ";
result += i.rating + " stars";
console.log(result)
});
The console log returns the following:
movieDB.js:1 Script Connected
movieDB.js:26 You have seen LOTR: Rating: 5
movieDB.js:26 You have seen Fast and the Furious: Rating: 1
movieDB.js:26 You have seen Let the Right One In: Rating: 5
movieDB.js:42 You have watched "LOTR" - 5 stars
movieDB.js:42 You have watched "Fast and the Furious" - 1 stars
movieDB.js:42 You have watched "Let the Right One In" - 5 stars
As you can see, both versions of the iteration ignore array object variables identified as false. What am I missing here?
Many thanks! Rick
Aucun commentaire:
Enregistrer un commentaire