我正在尝试使用嵌套在数组中的对象在JavaScript中编写程序。
但是在Web控制台中获取结果时遇到困难。任何帮助,将不胜感激。代码像这样-
var movies =[
{
title:"In Bruges",
hasWatched: true,
rating: 5
},
{
title:"Frozen",
hasWatched: false,
rating:4.5
},
{
title: "Mad Max Fury Road",
hasWatched: true,
rating:5
},
{
title: "Les Miserables",
hasWatched: false,
rating:3.5
}
]
movies.forEach(function (movie){
var result = "You Have ";
if(movies.hasWatched){
result += "Watched ";
} else {
result += "Not Watched ";
}
result += movies.title + " - ";
result += movies.rating + " stars.";
console.log(result);
})
输出应该像这样-
You Have Watched In Bruges - 5 stars.
You Have Not Watched Frozen - 4.5 stars.
You Have Watched Mad Max Fury Road - 5 stars.
You Have Not Watched Les Miserables - 3.5 stars.
但是它在我的mozila控制台中显示了不同的输出。像这样-
You Have Not Watched undefined - undefined stars 4 movie.js:32:11
正确的代码应该是什么?
用movies.hasWatched
替换movie.hasWatched
,依此类推
movies.forEach(function (movie){
var result = "You Have ";
if(movie.hasWatched){
result += "Watched ";
} else {
result += "Not Watched ";
}
result += movie.title + " - ";
result += movie.rating + " stars.";
console.log(result);
})