我知道这确实很基础,但我刚刚开始学习 Javascript 并练习一些数组和对象。我已经编写了一个基本的电影数据库,其中的对象存储在 var movie 中,但是控制台一直显示字符串 ive build,它应该在其中插入 movie.title 作为未定义。我缺少什么?
var movies = [
{
"title": "Armagedon",
"rating": 4.8,
"hasWatched": true,
},
{
"title": "Tomb Raider",
"rating": 2.6,
"hasWatched": true,
},
{
"title": "Fight Club",
"rating": 4.9,
"hasWatched": true,
}
];
movies.forEach(function(movie) {
var item = "You have ";
if (movies.hasWatched = true) {
item += "watched ";
} else {
item += "not seen ";
}
item += "\"" + movies.title + "\" - ";
item += movies.rating + " stars";
console.log(item);
})
这显然是一些非常基本的东西,所以对我放松一点!谢谢!
最佳答案
除了一个小错字之外,你都做得很棒...
只需将电影更改为电影即可
movies.forEach(function(movie) {
var item = "You have ";
if (movie.hasWatched = true) {
item += "watched ";
} else {
item += "not seen ";
}
item += "\"" + movie.title + "\" - ";
item += movie.rating + " stars";
console.log(item);
})
你可以尝试我对相同代码的一点简化
movies.forEach(movie => {
console.log(
`You have ${movie.hasWatched ? 'watched' : 'not seen'} "${movie.title}" - ${movie.rating}`
)
})
此代码使用箭头函数和字符串插值
关于迭代时 JavaScript 对象显示为 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221052/