[英]'for' loop not looping through object array properly
当我运行非常简单的以下代码时,由于某种原因,我在浏览器控制台中得到以下结果:“ 6您尚未观看未定义的未定义。” 谁能指出我的错误?
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 + "."); } }
将for
条件更改for
i < movies.length
; 你有一个额外的迭代。 并且您还需要引用movie movies[i]
以获得实际的电影,例如, movies[i].title
。
在上面的示例中,最后一个索引为3(项目编号为0、1、2、3),但是您的循环将进行到4,并将尝试查找movies[4].title
并返回未定义。
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 + ".");
}
}
您只是在访问时缺少索引标识符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.