有人可以解释为什么我的循环中未定义吗?我试图运行一个循环,让我知道如果我看到的东西以及评级是真的。我做错了什么?
var films = [
{
movie: "fast and the furious",
rating: 4,
seen: true
},
{
movie:"13 reasons why",
rating: 5,
seen: true
},
{
movie:"beaty and the beast",
rating: 4,
seen: false
}
];
films.forEach(function(movie){
var result = "You have ";
if(movie.seen) {
result += "watched ";
}
else{
result += "not seen ";
}
result += "\"" + films.movie + "\" - ";
result += films.rating + " stars";
console.log(result);
});
答案 0 :(得分:1)
您应该在迭代器函数中访问元素,而不是数组:
films.forEach(function(movie) {
var result = "You have ";
if (movie.seen) {
result += "watched ";
} else {
result += "not seen ";
}
result += "\"" + movie.movie + "\" - ";
result += movie.rating + " stars";
});
答案 1 :(得分:0)
您在函数中传递了一个movie参数。你应该用它来获得结果。
var films = [
{
movie: "fast and the furious",
rating: 4,
seen: true
},
{
movie:"13 reasons why",
rating: 5,
seen: true
},
{
movie:"beaty and the beast",
rating: 4,
seen: false
}
];
films.forEach(function(movie){
var result = "You have ";
if(movie.seen==true) {
result += "watched ";
}else{
result += "not seen ";
}
result += "\"" + movie.movie + "\" - ";
result += movie.rating + " stars";
console.log(result);
});

答案 2 :(得分:0)
foreach

使用其他变量输入{{1}}并使用相同的变量来读取属性。