当我运行非常简单的以下代码时,出于某种原因,我在浏览器控制台中得到以下结果:" 6您还没有看过undefined undefined。"有人能指出我的错误吗?
datalab: command not found

答案 0 :(得分:3)
您有一个对象数组,因此您需要引用每个数组元素的索引。您还需要将循环减少一个,因为数组索引从零开始,但长度不是。
var movies = [{
title: "The Mummy",
hasWatched: true,
stars: "5 stars"
},
{
title: "About A Boy",
hasWatched: true,
stars: "5 stars"
},
{
title: "It",
hasWatched: false,
stars: "5 stars"
},
{
title: "Cleopatra",
hasWatched: false,
stars: "5 stars"
}
];
for (var i = 0; i < movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
答案 1 :(得分:2)
将for
条件更改为i < movies.length
;你有一个额外的迭代。
您还需要引用movies[i]
来获取实际的电影,例如movies[i].title
。
在上面的示例中,最后一个索引是3(项目编号为0,1,2,3),但是您的循环将一直运行到4并且将尝试查找movies[4].title
并返回undefined。
答案 2 :(得分:1)
for (var i = 0; i <= movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
您在访问
时只是缺少索引标识符