当我运行以下非常简单的代码时,由于某种原因,我在浏览器控制台中得到以下结果:“6 You have not saw undefined undefined.”谁能指出我的错误吗?
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.hasWatched) {
console.log("You have watched " + movies.title + " " + movies.stars + ".");
} else {
console.log("You have not watched " + movies.title + " " + movies.stars + ".");
}
}
最佳答案
您有一个对象数组,因此需要引用每个数组元素的索引。您还需要将循环减少一,因为数组索引是从零开始的,但长度不是。
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 + ".");
}
}
关于javascript - “for”循环未正确循环对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416968/